我该如何解决这个问题?,我想将字符串表达式转换为 double 但它给出了错误。
void addProduct() async {
var result = await dbHelper.insert(Product(
name: txtName.text,
description: txtDescription.text,
unitPrice: double.tryParse(txtUnitPrice.text)));
Navigator.pop(context, true);
}
答案 0 :(得分:2)
double.tryParse
的签名是:
double? tryParse(String source)
double?
表示返回的值可能是 null
。
现在,参数 unitPrice
的类型为 double
,它不能接受 null
作为 double.tryParse
可能返回的输入。
??
空感知运算符提供故障安全值。示例: unitPrice: double.tryParse(txtUnitPrice.text) ?? 0.0));
double.parse
方法并简单地处理它在收到无效输入时抛出的 FormatException
。var result;
try {
result = await dbHelper.insert(Product(
name: txtName.text,
description: txtDescription.text,
unitPrice: double.parse(txtUnitPrice.text)));
} on FormatException {
// Do some action.
}
进一步阅读:Why nullable types?
答案 1 :(得分:0)
我解决了。 double.try 不是 double.tryParse