flutter 错误 : "A value of type ' Null' can't be assigned to a variable of type 'Product' ."

标签 flutter null non-nullable

我有一段代码是为以前版本的 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;
  }

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

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'.

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

var existingProduct = _items[existingProductIndex];

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

最佳答案

flutter 2.0(Null safety)之后,需要传非空值或者指定参数为nullable,

在您的情况下,您需要提及 key 为 nullable

产品?现有产品;

此外,您不需要传递 null 值,因为它默认为 null。

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

final _items = <Product>[];

关于 flutter 错误 : "A value of type ' Null' can't be assigned to a variable of type 'Product' .",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69384501/

相关文章:

flutter 错误 : Could not download bcprov-jdk15on. jar (org.bouncycaSTLe :bcprov-jdk15on:1. 56)

database - 使用Flutter从数据库中获取构建列表

mysql动态sql

java - 我如何使用来自 Kotlin 的不可空元素的 Java 集合?

pointers - 当类型在结构定义中明确指定时,无法推断类型参数 T 的类型

dart - Flutter - 泛型函数类型定义错误

Flutter 应用程序卡在 "Running Gradle task ' assembleDebug'

java - Java 是否允许可空类型?

sql - 将 "column = null"转换为 "column is null"?

objective-c - Objective C 到 Swift Nonnull 的转换