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;
}
}
CodePudding user response:
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;
}