flutter ExpansionTile 層級菜單的實現
開發(fā)環(huán)境
- win10
- Android Studio

效果
用于多級菜單展示,或選擇。
如 每個省,市,縣;
如 樹木的病蟲害;


關鍵代碼
@override
Widget build(BuildContext context) {
return ListTile(
title: _buildItem(widget.bean),
);
}
Widget _buildItem(NameBean bean){
if(bean.children.isEmpty){
return ListTile(
title: Text(bean.name),
onTap: (){
_showSeletedName(bean.name);
},
);
}
return ExpansionTile(
key: PageStorageKey<NameBean>(bean),
title: Text(bean.name),
children: bean.children.map<Widget>(_buildItem).toList(),
leading: CircleAvatar(
backgroundColor: Colors.green,
child: Text(bean.name.substring(0,1),style: TextStyle(color: Colors.white),),
),
);
}
分析
- api:ExpansionTile
- 算法:遞歸
1. ExpansionTile的使用
一般傳入三個參數
key,title,children;
- title:每一行上面的文字;
- children:菜單下面的子條目,是一個數組;
- key:根據源碼傳入PageStorageKey,用于保存滑動過程中的狀態(tài);
2. 遞歸
有的條目有子條目,有的沒有,通過遞歸的方式遍歷出每條數據;
通過 bean.children.isEmpty 來結束遞歸;
如 “直轄市”中的北京,下面沒有 “市”了,也就是children.isEmpty,此時應該結束遞歸,返回 ListTile;
如“省級行政單位” 下面的 “黑龍江”還有很多個“市”,還不需要繼續(xù)遍歷返回 層級菜單ExpansionTile;
3. 源碼
學習flutter,很多不了解的地方都可以試著看看對應源碼上面的注釋。
/// A single-line [ListTile] with a trailing button that expands or collapses
/// the tile to reveal or hide the [children].
///
/// This widget is typically used with [ListView] to create an
/// "expand / collapse" list entry. When used with scrolling widgets like
/// [ListView], a unique [PageStorageKey] must be specified to enable the
/// [ExpansionTile] to save and restore its expanded state when it is scrolled
/// in and out of view.
///
/// See also:
///
/// * [ListTile], useful for creating expansion tile [children] when the
/// expansion tile represents a sublist.
/// * The "Expand/collapse" section of
/// <https://material.io/guidelines/components/lists-controls.html>.
class ExpansionTile extends StatefulWidget {
上面一段是 ExpansionTile 的源碼注釋。
粗略一看會發(fā)現幾個熟悉的字眼:ListView,ListTile
不錯,實現層級菜單的效果,需要搭配使用ListView與ListTile,
上面貼的關鍵代碼中 _buildItem()方法恰恰符合這一點,
當有子條目的時候返回ExpansionTile ,當沒有子條目的時候返回 ListTile;
完整代碼--->gihub
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android向Excel寫入數據導出U盤并發(fā)送郵件
這篇文章主要為大家詳細介紹了Android將數據寫入Excel格式導出U盤、發(fā)送郵件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Android 使用jQuery實現item點擊顯示或隱藏的特效的示例
本篇文章主要介紹了Android 使用jQuery實現item點擊顯示或隱藏的特效的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
android工程下不能運行java main程序的解決方法
這篇文章主要介紹了android工程下不能運行java main程序的解決方法,需要的朋友可以參考下2014-05-05
Java4Android開發(fā)教程(二)hello world!
一般的開發(fā)教程都是介紹完安裝配置開發(fā)環(huán)境,緊接著來一篇hello world,算是國際慣例吧,我們當然也不能免俗,哈哈,各位看官請看好了!2014-10-10

