Reputation: 31
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
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.
??
null-aware operator. Example: unitPrice: double.tryParse(txtUnitPrice.text) ?? 0.0));
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