Home > Software design >  How do I get the sum of an object property in a list
How do I get the sum of an object property in a list

Time:01-25

 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),
  ];

How to get cart amount total?

CodePudding user response:

I'd do:

var result = 0;
for (var cart in CARTLIST) {
  result  = cart.amount;
}

It's short, dire

If you insist on doing it in a single expression, you can do:

var result = CARTLIST.fold<int>(0, (acc, cart) => acc   cart.amount);

Or you can do it in more steps, first extract the amounts, then add them up:

var result = CARTLIST.map((cart) => cart.amount).reduce((v1, v2) => v1   v2);

CodePudding user response:

final total = CARTLIST.reduce((prev, next)=>prev.amount next.amount);

read more about reduce method here: https://api.dart.dev/stable/1.10.1/dart-core/List/reduce.html

just a note, idiomatic Dart uses camelCase for variable name. So, cartList is more idiomatic than CARTLIST.

  •  Tags:  
  • dart
  • Related