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
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}
}
4 Comments
vbakale
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.
towhid
count is a map object. so you can write count['1'] to get its value 3vbakale
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?
towhid
The cart list should contain only product items. Why are you adding menu items to the cart? Also, can you share your code sample?