Sena
Sena

Reputation: 49

Trying to do a shpping cart project in flutter error is : The method '+' can't be unconditionally invoked because the receiver can be 'null'

Im getting error because of null safety. " _cart[index] += 1;"  in this line from operation part (+=). The error is : The method '+' can't be unconditionally invoked because the receiver can be 'null'.

class CartBloc with ChangeNotifier { Map<int, int> _cart= {};

  Map<int, int> get cart => _cart;

  void addToCart(index) {
    if (_cart.containsKey(index)) {
      
      _cart[index] += 1;
    } else {
      _cart[index] = 1;
    }
    notifyListeners();
  }

Upvotes: 1

Views: 37

Answers (1)

nvoigt
nvoigt

Reputation: 77334

Your compiler does not magically know that the return value of containsKey means that the indexer will return a non-null value. So you need to find a way to tell your compiler what you are doing, while staying with the functions and return types provided and without asking your compiler to assume things going on behind the scenes.

This should work:

void addToCart(int index) {
    final currentValue = _cart[index] ?? 0;
      
    _cart[index] = currentValue + 1;
    
    notifyListeners();
  }

You could also just use the function provided for this case:

void addToCart(int index) {
  _cart.update(index, (value) => value + 1, ifAbsent: () => 1);
  notifyListeners();
}

Upvotes: 3

Related Questions