源碼
class ExpansionTile extends StatefulWidget {
/// Creates a single-line [ListTile] with a trailing button that expands or collapses
/// the tile to reveal or hide the [children]. The [initiallyExpanded] property must
/// be non-null.
const ExpansionTile({
Key key,
this.leading,//標題左側要展示的widget
@required this.title,//要展示的標題widget
this.backgroundColor,//北京
this.onExpansionChanged,//列表展開收起的回調函數
this.children = const <Widget>[],//列表展開時顯示的widget
this.trailing,//標題右側要展示的widget
this.initiallyExpanded = false,//是否默認狀態下展開
}) : assert(initiallyExpanded != null),
}
demo:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
const CITY_NAMES = {
'北京':['東城區','西城區','海淀區','朝陽區','石景山區','順義區'],
'上海':['黃浦區','徐彙區','長寧區','靜安區','普陀區','閘北區'],
'廣州':['越秀','海珠','荔灣','天河','白雲','黃埔','南沙'],
'深圳':['南山','福田','羅湖','鹽田','龍崗','寶安','龍華'],
'杭州':['上城區','下城區','江乾區','拱墅區','西湖區','濱江區'],
'蘇州':['姑蘇區','吳中區','相城區','高新區','虎丘區','工業園區','吳江區'],
};
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("列表展開與收起"),
),
body: Container(
child: ListView(
children: _buildList(),
),
),
),
);
}
List<Widget> _buildList(){
List<Widget> widgets = [];
CITY_NAMES.keys.forEach((key){
widgets.add(_item(key, CITY_NAMES[key]));
});
return widgets;
}
Widget _item(String city,List<String> subCities){
return ExpansionTile(
title: Text(
city,
style: TextStyle(color: Colors.black54,fontSize: 20),
),
children: subCities.map((subCity)=>_buildSub(subCity)).toList(),
);
}
Widget _buildSub(String subCity){
//可以設置撐滿寬度的盒子 稱之爲百分百佈局
return FractionallySizedBox(
//寬度因子 1爲百分百撐滿
widthFactor: 1,
child: Container(
height: 50,
margin: EdgeInsets.only(bottom: 5),
decoration: BoxDecoration(color: Colors.lightBlueAccent),
child: Text(subCity),
),
);
}
}
效果: