Reputation: 113
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.
Upvotes: 4
Views: 7677
Reputation: 10865
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.
Upvotes: 17