4

I want to implement add to checkout in which number of items added is displayed. Plus button adds elements in list and minus removes elements from list. Goal is just to display particular items added and its quantity. I have added items in list want to count length of duplicate items. How we can do that in flutter?

1 Answer 1

7

here is your solution. [Null Safe]

void main() {
  List<int> items = [1, 1, 1, 2, 3, 4, 5, 5];

  Map<int, int> count = {};
  items.forEach((i) => count[i] = (count[i] ?? 0) + 1);

  print(count.toString()); // {1: 3, 2: 1, 3: 1, 4: 1, 5: 2}
}
Sign up to request clarification or add additional context in comments.

4 Comments

But how we can retrieve that length of duplicate item? as you mentioned in your example above there are three '1's and in the output it shows {1:3, ......}. So now i just want to display that 3 here.
count is a map object. so you can write count['1'] to get its value 3
Thank you it solved the question asked but now facing new issue. Whenever i add menu items to cart. The other items quantity also changes. Can we modify above solution for this also?
The cart list should contain only product items. Why are you adding menu items to the cart? Also, can you share your code sample?

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.