I have a shopping cart controller in dart/flutter with GetX statemanager. I have two different arrays with the same items. When a product is added to the cart, i want to first check if the item exists in a map. If so, i increment its occurrence, otherwise its added. The problem is that this only works for each product array separately.
E.g Array1 -> add item in Array1 to cart. this works perfectly;
Array2 -> add item in Array2 to cart. this also works perfectly.
Array1 and Array2 contain the same items;
Now if i want to add a product to the cart that has allready been added by the other array, it adds as a new entry instead of incrementing its occurrence.
code:
Product product1 = Product(id: 1, title: 'title - 1');
Product product2 = Product(id: 1, title: 'title - 1');
int count = 0;
while (count < 10) {
addToMap(product1);
addToMap(product2);
count++;
}
addToMap(Product product) {
if (hashMap.containsKey(product)) {
hashMap[product] += 1;
} else {
hashMap[product] = 1;
}
}
hashMap.forEach((key, value) {
print('key is ${key.title} and value is ${value}');
});
output:
key is title - 1 and value is 10
key is title - 1 and value is 10
expected output should be the following
key is title - 1 and value is 20