Osman
Osman

Reputation: 31

error: The argument type 'double?' can't be assigned to the parameter type 'double'. DART

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

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);
  }

Upvotes: 0

Views: 4550

Answers (2)

Osman
Osman

Reputation: 31

I solved it. Actually double.parse, not double.tryParse

Upvotes: 1

happy-san
happy-san

Reputation: 813

The signature of double.tryParse is:

double? tryParse(String source)

double? indicates that the returned value might be null.

Now, the parameter unitPrice is of type double which cannot accept null as an input which double.tryParse might return.


  • The simplest solution is to provide a fail-safe value by using ?? null-aware operator. Example:
    unitPrice: double.tryParse(txtUnitPrice.text) ?? 0.0));
  • But judging from your code, there might be no default value that you can put and you'd want the code to fail in a safe manner instead. Then you can use double.parse method and simply handle the FormatException it throws when invalid input is received.
var result; 

try {
  result = await dbHelper.insert(Product(
      name: txtName.text,
      description: txtDescription.text,
      unitPrice: double.parse(txtUnitPrice.text)));
} on FormatException {
  // Do some action.
}

Further reading: Why nullable types?

Upvotes: 2

Related Questions