错误:参数类型“double?”不能分配给参数类型“double”。镖

时间:2021-07-12 17:50:32

标签: dart

我该如何解决这个问题?,我想将字符串表达式转换为 double 但它给出了错误。

How can I solve this?,I want to convert string expression to double but it gives error.

    void addProduct() async {
    var result = await dbHelper.insert(Product(
        name: txtName.text,
        description: txtDescription.text,
        unitPrice: double.tryParse(txtUnitPrice.text)));
    Navigator.pop(context, true);
  }

2 个答案:

答案 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