How to solve: Operator can't be unconditionally invoked because the receiver can be null

Question

Asked by Carleton Y on December 06, 2021 (source).

I'm trying to add shopping functions to my app. I'm attempting to use ChangeNotifier to add a cart item counter and I am getting the error message 'error: The operator '-' can't be unconditionally invoked because the receiver can be 'null'. I'm new to coding so I have been unable to figure out a solution even after researching on SO. Thanks in advance for any help provided.

class EcommerceApp {

  static late SharedPreferences sharedPreferences;
  static String collectionUser = "users";
  static String collectionOrders = "orders";
  static String userCartList = 'userCart';
  static String subCollectionAddress = 'userAddress';

class CartItemCounter extends ChangeNotifier {
  final int _counter = EcommerceApp.sharedPreferences
      .getStringList(EcommerceApp.userCartList)
      ?.length - 1;

  int get count => _counter;
}

    
    }

Answer

Question answered by Chralle (source).

The return value of getStringList() has a chance of being null. Dart's Null-safety doesn't allow this. You can use the ?? operator to ensure another value in case of it being null. I think this might work:

class CartItemCounter extends ChangeNotifier {
  final int _counter = (EcommerceApp.sharedPreferences
      .getStringList(EcommerceApp.userCartList)
      .length ?? 0) - 1;

  int get count => _counter;
}
DART DART-NULL-SAFETY FLUTTER FLUTTER-CHANGE-NOTIFIER
SHARE: