Flutter之实现可折叠的列表

一、介绍

        1、使用flutter自带组件ExpansionTitle实现

        2、ExpansionTitle属性介绍

        

const ExpansionTile({
    Key key,
    this.leading, //标题左侧需要展示的Widget
    @required this.title, //要展示的标题Widget
    this.subtitle, 
    this.backgroundColor, //背景
    this.onExpansionChanged, //列表展开和收起的回调函数
    this.children = const [], //列表展开时候的Widget
    this.trailing, //标题有侧要展开的Widget
    this.initiallyExpanded = false, //默认状态下是否展开
    this.maintainState = false,
    this.tilePadding,//内边距
    this.expandedCrossAxisAlignment,//次轴对齐
    this.expandedAlignment, //主轴对齐
    this.childrenPadding, //子内容内边距
  })

二、实现

        1、首先准备一个数据源

        2、因为是下层展开,所以上层是个ListView,所以得使用ListView组件,在他的Widget中是一个ExpansionTile

三、源代码

class LivePage extends StatefulWidget {
  const LivePage({Key key}) : super(key: key);

  @override
  _LivePageState createState() => _LivePageState();
}

const citys = {
  "北京": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区", "顺义区", "海淀区"],
  "上海": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区", "顺义区", "海淀区"],
  "广州": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区", "顺义区", "海淀区"],
  "深圳": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区", "顺义区", "海淀区"],
};

class _LivePageState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "列表折叠和展开",
      home: Scaffold(
        body: Container(
          child: ListView(
            children: _buildList(),
          ),
        ),
      ),
    );
  }

  List _buildList() {
    List widgets = [];
    citys.keys.forEach((key) {
      widgets.add(_item(key, citys[key]));
    });

    return widgets;
  }

  Widget _item(String city, List listArea) {
    return ExpansionTile(
      title: Text(
        city,
        style: TextStyle(color: Colors.black54, fontSize: 20),
      ),
      children: listArea.map((area) => _buildArea(area)).toList(),
    );
  }

  Widget _buildArea(String area) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Container(
        alignment: Alignment.center,
        height: 50,
        margin: EdgeInsets.only(bottom: 3),
        decoration: BoxDecoration(color: Colors.lightBlueAccent),
        child: Text(area),
      ),
    );
  }
}

你可能感兴趣的:(Flutter,flutter,html5,html)