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

如何计算列表中对象属性的总和?以Cart列表amount总和为例

计算List中所有amount属性的总和

首先,明确你的Cart列表定义(已转义处理):

List<Cart> CARTLIST = [
  Cart(productName: "productName", amount: 123, image: "image", quantity: 3, desc: "KG", prodId: 1),
  Cart(productName: "productName", amount: 345, image: "image", quantity: 3, desc: "KG", prodId: 1),
];

下面是几种常用的计算总和的方式:

  • 使用fold方法(推荐,简洁高效)
    fold是Dart集合类提供的聚合方法,能直接对列表元素进行累加计算:

    // 如果amount是int类型,就用int totalAmount
    double totalAmount = CARTLIST.fold(0, (sum, cart) => sum + cart.amount);
    

    第一个参数0是累加的初始值,第二个参数定义累加逻辑——每次将当前元素的amount加到总和sum上。

  • 使用forEach循环
    初始化一个总和变量,遍历列表逐个累加:

    double total = 0;
    CARTLIST.forEach((cart) => total += cart.amount);
    
  • 使用普通for循环
    逻辑直观,适合刚接触Dart的开发者:

    double total = 0;
    for (var cart in CARTLIST) {
      total += cart.amount;
    }
    

注意:如果你的amount属性是整数类型(比如示例里的123、345),只需把代码中的double替换成int即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:21:23