颤动错误:“无法将‘Null’类型的值分配给‘Product’类型的变量。”

2 null non-nullable flutter

我有一个为以前版本的 Flutter 编写的代码,当我尝试在新版本中运行时出现一些错误。以下是我不知道如何解决的错误之一?

  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;
  }
Run Code Online (Sandbox Code Playgroud)

代码最后一行出现的错误消息是:

无法将“Null”类型的值分配给“Product”类型的变量。尝试更改变量的类型,或将右侧类型强制转换为“Product”。

编辑:除了解决我的问题的答案之外,我注意到我还可以在以下代码行中dynamic编写:Product?

var existingProduct = _items[existingProductIndex];
Run Code Online (Sandbox Code Playgroud)

我很想知道哪种解决方案更好?为什么?

Moh*_*hri 6

flutter 2.0(空安全)之后,您需要传递非空值或指定参数可为空,

在您的情况下,您需要将 key 指定为可为空

Product? existingProduct;

另外,您不需要传递空值,因为默认情况下它具有空值。

或者使列表不可为空,因此您不需要在上面提到,但如果它可以为空,则添加?到它。

final _items = <Product>[];
Run Code Online (Sandbox Code Playgroud)