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

Flutter/Dart中按卖家ID分组数组并格式化数据的实现

如何将购物车数据按商家分组格式化(Flutter)

原始数据

final info = [
  {
    "id": "cart1",
    "product": {"id": "01"},
    "seller": {"id": "seller1"},
    "quantity": 8,
    "amount": 2544,
  },
  {
    "id": "cart2",
    "product": {"id": "02"},
    "seller": {"id": "seller1"},
    "quantity": 1,
    "amount": 318,
  },
  {
    "id": "cart3",
    "product": {"id": "03"},
    "seller": {"id": "seller2"},
    "quantity": 1,
    "amount": 200,
  },
];

目标格式

final result = [
  {
    "seller": "seller1",
    "products": [
      {"productId": "01", "quantity": 8, "amount": 2544},
      {"productId": "02", "quantity": 1, "amount": 318},
    ],
    "price": 2862
  },
  {
    "seller": "seller2",
    "products": [
      {"productId": "03", "quantity": 1, "amount": 200},
    ],
    "price": 200
  },
];

实现步骤与代码

核心思路是先用Map按商家ID临时分组,再将分组数据转换为目标列表格式:

void main() {
  final info = [
    {"id": "cart1", "product": {"id": "01"}, "seller": {"id": "seller1"}, "quantity": 8, "amount": 2544},
    {"id": "cart2", "product": {"id": "02"}, "seller": {"id": "seller1"}, "quantity": 1, "amount": 318},
    {"id": "cart3", "product": {"id": "03"}, "seller": {"id": "seller2"}, "quantity": 1, "amount": 200},
  ];

  // 用Map存储商家分组数据,key为商家ID
  final Map<String, Map<String, dynamic>> sellerGroups = {};

  for (final item in info) {
    final sellerId = item["seller"]["id"] as String;
    final productId = item["product"]["id"] as String;
    final quantity = item["quantity"] as int;
    final amount = item["amount"] as int;

    // 初始化商家分组结构(如果不存在)
    if (!sellerGroups.containsKey(sellerId)) {
      sellerGroups[sellerId] = {
        "seller": sellerId,
        "products": [],
        "price": 0,
      };
    }

    // 添加当前商品到对应商家的列表
    sellerGroups[sellerId]!["products"].add({
      "productId": productId,
      "quantity": quantity,
      "amount": amount,
    });

    // 累加商家总金额
    sellerGroups[sellerId]!["price"] = (sellerGroups[sellerId]!["price"] as int) + amount;
  }

  // 将Map的值转为List,得到最终结果
  final result = sellerGroups.values.toList();

  // 打印验证结果
  print(result);
}

项目优化建议

实际开发中更推荐用自定义类替代Map,类型更安全、可读性更强:

class SellerGroup {
  final String sellerId;
  final List<CartProduct> products;
  final int totalPrice;

  SellerGroup({
    required this.sellerId,
    required this.products,
    required this.totalPrice,
  });

  // 转为目标JSON格式的方法
  Map<String, dynamic> toJson() {
    return {
      "seller": sellerId,
      "products": products.map((p) => p.toJson()).toList(),
      "price": totalPrice,
    };
  }
}

class CartProduct {
  final String productId;
  final int quantity;
  final int amount;

  CartProduct({
    required this.productId,
    required this.quantity,
    required this.amount,
  });

  Map<String, dynamic> toJson() {
    return {
      "productId": productId,
      "quantity": quantity,
      "amount": amount,
    };
  }
}

用类实现可以避免Map的类型转换风险,后期维护也更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:30:42