Home > database >  dart null safty issue when try to add value to map element
dart null safty issue when try to add value to map element

Time:12-03

I am using Dart but i am facing null safty issue with following code

RxMap<Product,int>cartItems=Map<Product,int>().obs;
void updateCart(Product product,String type){
  if(type=="plus") {
    cartItems.value[product]  ;
  }
  else {
    cartItems.value[product]--;
  }

}

i got the following error message

the method ' ' can't be unconditionally invoked because the receiver can be 'null'

i tried to add null check to the target as following

cartItems.value![product]  ;

CodePudding user response:

You can give a default value if null.

cartItems.value[product]??0  1

Or force assert to non null value like this.It may throw exception if element not present in HashMap

cartItems.value[product]! 1

In your question you are asserting not null for HashMap not the value of the HashMap.

CodePudding user response:

The problem is that cartItems.value is a Map and it's possible that cartItems.value[product] is null. In this case you can't add or remove 1 to null. So you should do like the following:

if (type == "plus") {
  cartItems.value[product] = (cartItems.value[product] ?? 0)   1;
} else {
  cartItems.value[product] = (cartItems.value[product] ?? 0) - 1;
}

Using (cartItems.value[product] ?? 0) you're saying that if cartItems.value[product] is null 0 is used instead.

Also note that in the else clause, when cartItems.value[product] == null, you're trying to remove 1 to something that doesn't exist, so in that case it may be best to throw an exception:

int? currentValue = cartItems.value[product];
if (currentValue == null) {
  throw Exception('Trying to remove on a null object');
}
cartItems.value[product] = currentValue - 1;
  • Related