//我得到一个错误在widget.product.id,//参数类型为int?'不能赋值给形参类型'int'。
updateRoutine() async {
final productCollection = widget.isar.products;
await widget.isar.writeTxn((isar) async {
final product = await productCollection.get(widget.product.id);
product!
..name = nameController.text
..price = double.parse(priceController.text)
..quantity = int.parse(quantityController.text);
await productCollection.put(product);
});
}
您的productCollection.get
只接受非空int,而您的widget.product.id
可以为空。
修复这个问题的一种方法是,如果该函数为null,则不调用该函数:
updateRoutine() async {
final productCollection = widget.isar.products;
await widget.isar.writeTxn((isar) async {
int? id = widget.product.id;
if (id != null) {
final product = await productCollection.get(id);
product!
..name = nameController.text
..price = double.parse(priceController.text)
..quantity = int.parse(quantityController.text);
await productCollection.put(product);
}
});
}
或者如果您的id为null(本例为0),则为该参数添加默认值
updateRoutine() async {
final productCollection = widget.isar.products;
await widget.isar.writeTxn((isar) async {
final product = await productCollection.get(widget.product.id ?? 0); //ADD ?? 0
product!
..name = nameController.text
..price = double.parse(priceController.text)
..quantity = int.parse(quantityController.text);
await productCollection.put(product);
});
}
您可以强制展开产品id,然后将其分配给int变量
还有其他方法
- 给出默认值:int a = product。id ? ?1
- 强制unwrap: int a =prododuct.id !
- make可选变量:int?a = product.id