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