当前位置: 移动技术网 > IT编程>移动开发>Android > flutter ExpansionTile 层级菜单的实现

flutter ExpansionTile 层级菜单的实现

2019年09月06日  | 移动技术网IT编程  | 我要评论

莲都二手房,陕西省第十五届运动会,新先锋白菜论坛

开发环境

  • 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,用于保存滑动过程中的状态;

2. 递归

有的条目有子条目,有的没有,通过递归的方式遍历出每条数据;

通过 bean.children.isempty 来结束递归;
如 “直辖市”中的北京,下面没有 “市”了,也就是children.isempty,此时应该结束递归,返回 listtile;
如“省级行政单位” 下面的 “黑龙江”还有很多个“市”,还不需要继续遍历返回 层级菜单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 的源码注释。
粗略一看会发现几个熟悉的字眼:listview,listtile
不错,实现层级菜单的效果,需要搭配使用listview与listtile,
上面贴的关键代码中 _builditem()方法恰恰符合这一点,
当有子条目的时候返回expansiontile ,当没有子条目的时候返回 listtile;

完整代码--->

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网