Flutter产品搜索页:TextField转Double遇格式异常的解决方法
解决价格搜索的格式异常问题
问题核心是直接调用double.parse()转换用户输入——当输入非数字字符串时,这个方法会抛出FormatException,导致整个筛选逻辑异常中断。
你可以用double.tryParse()替代,它在转换失败时会返回null而非抛出异常,再通过判断转换结果是否有效来执行价格匹配逻辑。修改后的代码如下:
if (selectedSearchText.value != '') { final inputPrice = double.tryParse(searchText.text); filteredList.value = filteredList.where((product) => product.title.toUpperCase().contains(selectedSearchText.value.toUpperCase()) || product.brand!.name.toUpperCase().contains(selectedSearchText.value.toUpperCase()) || (inputPrice != null && product.price == inputPrice) ).toList(); }
关键细节:
double.tryParse(searchText.text):尝试将输入文本转为double类型,成功返回对应数值,失败返回null- 价格匹配条件
(inputPrice != null && product.price == inputPrice):仅当输入能转成有效数字时,才触发价格精确匹配;否则该条件不生效,仅按标题、品牌筛选
如果你的需求是模糊匹配价格(比如输入"10"能匹配10.99、100等包含"10"的价格),可以直接将价格转为字符串做包含判断,完全避免数字转换的异常问题:
if (selectedSearchText.value != '') { final searchStr = selectedSearchText.value.toUpperCase(); filteredList.value = filteredList.where((product) => product.title.toUpperCase().contains(searchStr) || product.brand!.name.toUpperCase().contains(searchStr) || product.price.toString().toUpperCase().contains(searchStr) ).toList(); }
内容的提问来源于stack exchange,提问作者user22362195
相关产品推荐
相关产品推荐

