Flutter error : "A value of type 'Null' can't be assigned to a variable of type 'Product'."
Solution 1
After flutter 2.0 (Null safety), You need to either pass non-null values or specify that parameter is nullable,
here in your case, you need to mention key as nullable
Product? existingProduct;
Also, you do not need to pass null values as it is had by default null.
or make a list non-nullable, thus you do not need mention above one but if it is nullable then add ?
to it.
final _items = <Product>[];
Solution 2
Change this line:
var existingProduct = _items[existingProductIndex];
to this:
Product? existingProduct = _items[existingProductIndex];
Typing the existingProduct
variable with Product?
means the existingProduct
is nullable and it can be assigned the null
value.
ensan3kamel
Updated on January 01, 2023Comments
-
ensan3kamel over 1 year
I have a code that is written for previous version of the Flutter and has some errors when I try to run in the new version. The following is one of the errors I don't know how to resolve?
Future<void> deleteProduct(String id) async { final url = Uri.parse( 'https://flutter-update.firebaseio.com/products/$id.json?auth=$authToken'); final existingProductIndex = _items.indexWhere((prod) => prod.id == id); var existingProduct = _items[existingProductIndex]; _items.removeAt(existingProductIndex); notifyListeners(); final response = await http.delete(url); if (response.statusCode >= 400) { _items.insert(existingProductIndex, existingProduct); notifyListeners(); throw HttpException('Could not delete product.'); } existingProduct = null; }
The error message that occurs in the last line of the code is:
A value of type 'Null' can't be assigned to a variable of type 'Product'. Try changing the type of the variable, or casting the right-hand type to 'Product'.
EDIT: Beside the answers that resolved my problem, I noticed that I can also write
dynamic
instead ofProduct?
in the following line of the code:var existingProduct = _items[existingProductIndex];
And I am interested to know which solution is better? Why?