You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何处理分组数据在ListView展示唯一分组名及对应子产品

问题原因

当前你直接遍历所有产品条目渲染,每个产品条目里都写了分组名称的渲染逻辑,导致每个产品前面都会重复输出所属分组名。

解决步骤

1. 先对原始产品列表按分组聚合

先把_mOfferList按分组字段offerBaseProductBrandTitle做聚合处理,把同一个分组的产品放到同一个数组里:

// 处理数据:按分组名聚合产品,注意把代码里的「你的产品实体类」替换成你实际的产品类名
Map<String, List<你的产品实体类>> groupedOffers = {};
_mOfferList?.forEach((offer) {
  String groupName = offer.offerBaseProductBrandTitle;
  if (!groupedOffers.containsKey(groupName)) {
    groupedOffers[groupName] = [];
  }
  groupedOffers[groupName]!.add(offer);
});
// 把分组映射转成列表,方便后续遍历
List<MapEntry<String, List<你的产品实体类>>> groupEntries = groupedOffers.entries.toList();

2. 修改ListView构建逻辑

不要直接遍历原始产品列表,改为遍历聚合后的分组列表,每个分组先渲染一次分组名,再遍历渲染该分组下的所有产品:

body: ListView.builder(
  scrollDirection: Axis.vertical,
  shrinkWrap: true,
  // 遍历的数量改成分组的数量,不是原始产品的数量
  itemCount: groupEntries.length,
  itemBuilder: (BuildContext context, int groupIndex) {
    var currentGroup = groupEntries[groupIndex];
    String groupName = currentGroup.key;
    List<你的产品实体类> groupProducts = currentGroup.value;
    return Card(
      elevation: 1,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 每个分组仅渲染一次分组名称
            Text(
              groupName,
              style: const TextStyle(fontSize: 13.0),
            ),
            const SizedBox(height: 8),
            // 遍历渲染当前分组下的所有产品,添加左侧缩进实现层级效果
            ...groupProducts.asMap().entries.map((productEntry) {
              int productSeq = productEntry.key;
              var product = productEntry.value;
              return Padding(
                padding: const EdgeInsets.only(left: 24.0),
                child: Text(
                  "${String.fromCharCode(97 + productSeq)}) ${product.offerTitle ?? ''}",
                  style: const TextStyle(fontSize: 13.0),
                ),
              );
            }).toList()
          ],
        ),
      ),
    );
  }
)

修改后即可实现你要的分组展示效果,同一个分组的产品都会聚合在对应分组名下方,不会重复出现分组名。

内容的提问来源于stack exchange,提问作者Flutter Box

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:24:09