Flutter如何过滤List<Device>重复分类 使GridView不展示重复分类名称
实现方案
核心逻辑为对Device实例的Category字段做去重处理,可根据你的实际业务需求选择以下两种实现方式:
方式1:提取去重后的纯分类名列表(适合仅需展示分类名称的场景)
List<Device> _deviceList = [ Device(id:'d1', Name:'Fan', Category:'LivingRoom'), Device(id:'d2', Name:'Tv', Category:'LivingRoom'), Device(id:'d3', Name:'Light', Category:''), Device(id:'d4', Name:'refrigerator', Category:'Kitchen'), ]; // 提取所有分类值存入Set自动去重,空分类会被单独保留 Set<String> categorySet = _deviceList.map((device) => device.Category).toSet(); List<String> uniqueCategories = categorySet.toList(); // 可选操作:过滤掉空分类 // uniqueCategories.removeWhere((cate) => cate.isEmpty); // 可选操作:自定义分类排序 // uniqueCategories.sort((a, b) => a.compareTo(b));
方式2:保留每个分类对应的首个Device实例(适合点击分类后需要关联查询该分类下设备的场景)
Set<String> usedCategory = {}; List<Device> uniqueDeviceList = _deviceList.where((device) { if (usedCategory.contains(device.Category)) return false; usedCategory.add(device.Category); return true; }).toList();
GridView中使用示例(以方式1的分类列表为例)
GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 8, crossAxisSpacing: 8 ), itemCount: uniqueCategories.length, itemBuilder: (context, index) { final category = uniqueCategories[index]; // 空分类默认展示为「未分类」 final showCateName = category.isEmpty ? "未分类" : category; // 替换为你自己的分类卡片组件即可 return Center(child: Text(showCateName)); } )
效果参考

内容的提问来源于stack exchange,提问作者Azorahai
相关产品推荐
相关产品推荐

