Flutter下拉菜单按部门分类:解决标签重复并实现层级展示
解决方案
问题分析
原代码存在两个核心问题:
- 遍历
item.values时,每个非List类型字段都会重复添加department作为加粗项,导致父标签大量重复 - 错误地用
department作为父标签,而非需求中的name,且层级逻辑混乱
修正代码
List<Map<String, dynamic>> category = [ { "name": "One", "detail": ['11', '12', '13', '14'], "department": "aaa", }, { "name": "two", "detail": ['21', '22', '23', '24'], "department": "bbb", }, { "name": "three", "detail": ['31', '32', '33', '34'], "department": "ccc", }, { "name": "four", "detail": ['41', '42', '43', '44'], "department": "aaa", }, { "name": "five", "detail": ['41', '42', '43', '44'], "department": "aaa", }, ]; List<Map<String, dynamic>> data = []; for (final item in category) { // 仅保留department为"aaa"的数据 if (item["department"] == "aaa") { // 添加name作为加粗父标签 data.add({'value': item['name'], 'bold': true}); // 遍历detail数组,添加子项 for (final detailItem in item['detail']) { data.add({'value': detailItem, 'bold': false}); } } }
代码说明
- 数据筛选:通过
item["department"] == "aaa"精准过滤出目标数据 - 层级构建:
- 每个符合条件的分类,先添加
name作为加粗父标签 - 再遍历
detail数组,逐个添加子项并标记为非加粗
- 每个符合条件的分类,先添加
- 避免重复:每个分类仅生成一个父标签,彻底解决原代码的重复问题
最终生成的data结构完全匹配需求:
- One(加粗)
- 11
- 12
- 13
- 14
- four(加粗)
- 41
- 42
- 43
- 44
- five(加粗)
- 41
- 42
- 43
- 44
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

