Flutter中ListView.builder实现列表项分组及分组商品总数统计
问题原因
你之前的分组实现存在两处核心错误:
- 定义的
Map<String,Product>类型仅能存储单个商品对象,无法统计每个位置下的商品总数,计数场景应该使用Map<String, int>结构,key存储位置名称,value存储对应位置的商品数量。 - 遍历逻辑中的判断条件
product.location.name==product.location.name是恒成立的无效判断,无法实现分组逻辑。
无第三方依赖的实现方案
第一步:遍历商品列表完成分组计数
在拿到商品列表数据后、构建组件前执行统计逻辑,避免在构建过程中重复计算浪费性能:
// 存储分组结果:key=位置名称,value=对应位置商品总数 final Map<String, int> locationCountMap = {}; for (final product in listViewProductsRecordList) { final String currentLocationName = product.location.name; if (locationCountMap.containsKey(currentLocationName)) { // 位置已存在,计数+1 locationCountMap[currentLocationName] = locationCountMap[currentLocationName]! + 1; } else { // 位置第一次出现,初始化计数为1 locationCountMap[currentLocationName] = 1; } }
第二步:改造ListView组件渲染分组结果
此时渲染数据源是分组后的统计结果,不再是原始商品列表:
ListView.builder( padding: EdgeInsets.zero, scrollDirection: Axis.horizontal, // 条目总数为分组后的位置数量 itemCount: locationCountMap.length, itemBuilder: (context, index) { // 按索引取出对应位置的名称和商品数 final locationName = locationCountMap.keys.elementAt(index); final productNum = locationCountMap[locationName]; return Text("$locationName: $productNum Products"); } )
补充说明:如果存在位置名称为空的异常场景,可以在取值时增加空值兜底,比如设置默认展示文本为「未知位置」即可。
内容的提问来源于stack exchange,提问作者EMT
相关产品推荐
相关产品推荐

