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

在Flutter中如何过滤处理列表,实现同名称商品数量累加合并?

Flutter 合并相同名称商品列表实现方案

核心实现逻辑如下:

  • 用临时Map存储相同名称商品的累计数量,避免重复遍历
  • 遍历原始列表时将字符串类型的数量转为数值累加
  • 最终将Map转换为目标格式的列表即可

代码示例(直接处理Map列表)

void main() {
  List<Map<String, String>> originProducts = [
    {"name": "apple", "qty": "5"},
    {"name": "apple", "qty": "2"},
    {"name": "orange", "qty": "3"},
  ];

  Map<String, int> countMap = {};
  for (var item in originProducts) {
    String name = item['name']!;
    int qty = int.parse(item['qty']!);
    countMap[name] = (countMap[name] ?? 0) + qty;
  }

  // 生成合并后的列表
  List<Map<String, String>> mergedProducts = countMap.entries.map((e) {
    return {"name": e.key, "qty": e.value.toString()};
  }).toList();

  print(mergedProducts); // 输出:[{name: apple, qty: 7}, {name: orange, qty: 3}]
}

注意事项

  • 若数量字段可能存在非数字格式,建议替换int.parse为int.tryParse并添加异常处理逻辑
  • 如果需要保留商品在原始列表中首次出现的顺序,可在遍历时额外记录顺序,最终转换时按该顺序排序

内容的提问来源于stack exchange,提问作者muhammed jasir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:54:04