可以把ExpansionTile当做ListView的子组件,而展开部分又是ExpansionTile的children子组件。
import 'package:flutter/material.dart';
const List<Object> CITY_ALL = [
{
'title': '湖南',
'district': ['岳麓区', '高新区', '长沙市', '岳阳', '娄底', '浏阳'],
},
{
'title': '动漫',
'district': ['a', 'b', 'v', 'v', 'f', 'h'],
},
{
'title': '技术',
'district': ['vue', 'uniapp', 'flutter', 'android', 'ios', 'java', 'rust'],
},
{
'title': '深圳',
'district': ['南山', '福田', '罗湖', '盐田', '龙岗', '宝安', '龙华'],
},
];
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("列表展开与收起"),
),
body: Container(
child: ListView(
children: _buildList(),
),
),
),
);
}
List<Widget> _buildList() {
return CITY_ALL.map((item) {
item as Map;
return _item(item["title"], item["district"]);
}).toList();
}
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: 1),
decoration: BoxDecoration(color: Colors.black12),
child: Text(subCity),
),
);
}
}
网友评论