在Flutter中实现三级联动组件,可以通过以下步骤实现:
核心思路
使用三个DropdownButton组件,通过状态管理实现级联效果。当上级选择改变时,下级选项随之更新。
实现代码
import 'package:flutter/material.dart';
class TriplePicker extends StatefulWidget {
@override
_TriplePickerState createState() => _TriplePickerState();
}
class _TriplePickerState extends State<TriplePicker> {
// 模拟数据(省份-城市-区县)
final Map<String, Map<String, List<String>>> data = {
'北京市': {
'市辖区': ['东城区', '西城区', '朝阳区', '丰台区'],
},
'广东省': {
'广州市': ['天河区', '越秀区', '海珠区'],
'深圳市': ['福田区', '罗湖区', '南山区'],
},
};
String? selectedProvince;
String? selectedCity;
String? selectedDistrict;
List<String> get provinces => data.keys.toList();
List<String> get cities => selectedProvince != null
? data[selectedProvince]!.keys.toList()
: [];
List<String> get districts => (selectedProvince != null && selectedCity != null)
? data[selectedProvince]![selectedCity]!
: [];
@override
Widget build(BuildContext context) {
return Row(
children: [
// 省份选择
Expanded(
child: DropdownButton<String>(
isExpanded: true,
value: selectedProvince,
hint: Text('选择省份'),
items: provinces.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedProvince = newValue;
selectedCity = null; // 重置城市
selectedDistrict = null; // 重置区县
});
},
),
),
SizedBox(width: 10),
// 城市选择
Expanded(
child: DropdownButton<String>(
isExpanded: true,
value: selectedCity,
hint: Text('选择城市'),
items: cities.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedCity = newValue;
selectedDistrict = null; // 重置区县
});
},
),
),
SizedBox(width: 10),
// 区县选择
Expanded(
child: DropdownButton<String>(
isExpanded: true,
value: selectedDistrict,
hint: Text('选择区县'),
items: districts.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedDistrict = newValue;
});
},
),
),
],
);
}
}
使用方式
// 在页面中直接使用
TriplePicker()
关键点说明
- 数据管理:使用嵌套Map结构存储三级数据
- 状态联动:通过
setState实现选择变化时的界面更新
- 级联重置:上级选项变化时清空下级选项
- 空值处理:使用
hint提示用户选择
优化建议
- 可封装为独立组件,支持数据注入
- 添加加载状态和空数据提示
- 支持自定义样式
- 可改用
PopupMenuButton实现更灵活的UI
这个实现方案简洁有效,适合大多数三级联动场景。