skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search