flutternullnon-nullable

Flutter error : "A value of type 'Null' can't be assigned to a variable of type 'Product'."


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 of Product? in the following line of the code:

var existingProduct = _items[existingProductIndex];

And I am interested to know which solution is better? Why?


Solution

  • 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>[];