Home > Net >  is possible to insert item into map if it does not exist and otherwise increment its occurrence in d
is possible to insert item into map if it does not exist and otherwise increment its occurrence in d

Time:10-11

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

CodePudding user response:

The problem with your hashMap is the key. product1 and product2 are 2 different instances, that mean 2 different keys. Instead of using the whole class, try using only the id. It should look something like this:

 addToMap(Product product) {
  if (hashMap.containsKey(product.id)) {
    hashMap[product.id]  = 1;
  } else {
    hashMap[product.id] = 1;
  }
}

this way even if the instances are different, the id will be the same.

CodePudding user response:

Correct solution is as follows.

as suggested by @Razvan. i did use the product.id as the key in the hashmap. this solution works well, but if your like me and you want to be able to extract objects from from the ints in the hashmap. you have to use a List. the list holds each item only once. the hashmap keeps track of how many times an item is added to the list. and if you wan to be able to calculate price for example, use a simple loop over the hashmap and mutiply price by quantity.

Map hashMap = HashMap<int, int>();
List<T> products = <T>();

//calculate price for a item
hashMap.forEach((key, value) {
      print('Key is $key and value is $value');
      for (var element in products) {
        print('Price is ${element.price * value}');
      }
    });

addToMap(Product product) {
  if (hashMap.containsKey(product.id)) {
    hashMap[product.id]  = 1;
  } else {
    products.add(product)
    hashMap[product.id] = 1;
  }
  • Related