Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of value in a collection using flutter

Tags:

flutter

dart

I have a list/collection and I need to get the sum of all prices in this list.

cart_items = [
    {
        "id": 144,
        "created_at": "2019-04-04 14:42:04",
        "updated_at": "2019-04-04 14:42:04",
        "cart_id": "3",
        "client_id": "83",
        "product_id": "6",
        "quantity": "1",
        "price": "1500",
        "name": "Cucumber (2Pcs)",
        "image": "products/es4eGjkgQ6MvzTaMyX4iXWjcSX03mVk3QB9oODWk.jpeg",
       },
    {
        "id": 145,
        "created_at": "2019-04-04 14:42:09",
        "updated_at": "2019-04-04 14:42:09",
        "cart_id": "3",
        "client_id": "83",
        "product_id": "5",
        "quantity": "1",
        "price": "2000",
        "name": "Cauliflower",
        "image": "products/lVZ31zORzltyVIDXhHoCWUgjTlal7cWd7pI8DL2V.jpeg",
        }
]

I have been trying to use the reduce method on this collection/list but I don't know how to specify that I need to get the sum for price.

like image 728
Hussein Haule Avatar asked Nov 06 '25 23:11

Hussein Haule


1 Answers

Here you go:

cart_items.map<int>((m) => int.parse(m["price"])).reduce((a,b )=>a+b)

As @user3612643 pointed out in comment, this does not work if the collection is empty, so condition check for it required in that case.

like image 80
Harsh Bhikadia Avatar answered Nov 09 '25 18:11

Harsh Bhikadia