The property 'quantity' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.')
This is because you are trying to access a valid in a map, by passing a key to it.
If the id exist as a key in the map, then you will have a cartitem object indeed. But if the id does not exist, the result will be null, and your operation will become null.quantity
.
The receiver here is your cartitem object.
Try:
_items[productID]!.quantity
This way, you promise dart that it's impossible to be null. Your error will go away, but this is a risky operation. The proper way to fix this, is make sure it's not null, before calling quantity on it.
Before your if statement, do this:
if (_items[productID] != null) if(_items[productID]!.quantity == 1) _items.remove(productID);
This way, you will for sure not make it into your second if statement, unless cartitem is not null, 100%.
![Hammad Khan](https://i.stack.imgur.com/MFIuz.jpg?s=256&g=1)
Hammad Khan
Humble, down to earth, experience software Engineer 12+ years of industry experience in ASP.NET, SQL Server, C/C++, Web Development, Automation
Updated on January 01, 2023Comments
-
Hammad Khan over 1 year
Relevent code
import 'package:flutter/foundation.dart'; class CartItem { final String id; final String title; final int quantity; final double price; CartItem({ required this.id, required this.title, required this.quantity, required this.price, }); } class Cart with ChangeNotifier { Map<String, CartItem> _items = {}; // see that I have initialized the items
The code where I am getting the null safety error 'The property 'quantity' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').' The error I am getting is on the below quantity variable. I am not sure how to fix it. I have watched videos which talked about int?, ! and ?: operators but this particular scenario was not covered.
if (_items[productID].quantity == 1) _items.remove(productID);
Additional questions, what is the receiver here that the error is point to which can be null?
-
Iván Yoed over 2 yearsDoes this answer your question? The property 'isEmpty" can't be unconditionally accessed because the receiver can be 'null'
-
Hammad Khan over 2 years@IvánYoed yes this had to do with null safety which was introduced into flutter later. This is now resolved. Thx
-
Iván Yoed over 2 yearsI see! Thanks to you @Hammad!
-
-
Hammad Khan almost 3 yearsAs you can see in the code above, I have made them
required
, additionally if i try quanity = 0, in constructor, I get error. Not sure what to do -
Huthaifa Muayyad almost 3 yearsMy bad, I edited my answer.