1

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;
}

    
    }
Carleton Y
  • 289
  • 5
  • 17

1 Answers1

2

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;
}
Zahra
  • 2,231
  • 3
  • 21
  • 41
Chralle
  • 36
  • 4
  • 3
    It is not `SharedPreferences` that is a nullable type but rather the return value of `getStringList` is `List?` (https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences/getStringList.html). You must use `?.length` here rather than `.length` but I think otherwise this answer is correct. – mmcdon20 Dec 06 '21 at 23:40
  • 1
    @chralle if you can edit your answer to reflect comment by mmcdon20 I will mark your answer as accepted as the code has definitely resolved my problem. Thank you. – Carleton Y Dec 07 '21 at 00:05