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]++;
2
Answers
You can give a default value if null.
Or force assert to non null value like this.It may throw exception if element not present in HashMap
In your question you are asserting not null for HashMap not the value of the HashMap.
The problem is that
cartItems.value
is a Map and it’s possible thatcartItems.value[product]
isnull
. In this case you can’t add or remove1
tonull
.So you should do like the following:
Using
(cartItems.value[product] ?? 0)
you’re saying that ifcartItems.value[product]
isnull
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: