4

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.

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

5 Comments

could you also upvote the answer, if it is what you were looking for.
This did not solve the issue, I am getting the result separately. refer here: stackoverflow.com/questions/65644043/…
Breaks if the collection is empty.
@user3612643 Thanks for pointing this out. Will put this in answere
For the sake of completeness: In 2021 you can replace the reduce((a,b)=>a+b) part by just calling .sum on the list. Just import import 'package:collection/collection.dart'; first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.