I am creating a product search screen with textformfield
i want to search on product title, brand name or price,
In my productModel price is double,
if i type any number its working fine but when i type like apple or any character string its showing exception and result into unexpected search products,
how should i code for comparing my product’s price to textfield value
if(selectedSearchText.value != '') {
filteredList.value = filteredList.where((product) =>
product.title.toUpperCase().contains(selectedSearchText.value.toUpperCase()) ||
product.brand!.name.toUpperCase().contains(selectedSearchText.value.toUpperCase()) ||
product.price==double.parse(searchText.text)).toList();
}
and error is
Format exception invalid double
2
Answers
Above line is the main result of your error as you are using parse to convert string into double,
parse throws an exception when inputed string is not in correct format.
but tryParse will return false on invalid input string
this is the main difference between tryParse and parse
so correct your line with
The error you’re encountering is due to attempting to parse a non-numeric string into a double using double.parse(). To avoid this exception, you need to ensure that the input string is a valid double before parsing it.
You can achieve this by first checking if the input string can be parsed into a double before performing the comparison. Here’s how you can modify your code to handle this:
In this modified version, double.tryParse() is used to check if the search text can be parsed into a double. If it can, it compares the parsed double value with the product’s price. If not, it only searches in the product’s title and brand name. This should prevent the format exception you’re encountering.
Good Luck!