Flutter中如何检测空TextField并正确获取double值避免格式异常
你遇到的异常是因为double.parse仅支持合法的数字字符串输入,空字符串、非数字格式的内容传入时都会直接抛出FormatException,可以通过以下方式解决:
核心修复方案
使用double.tryParse替代double.parse,该方法转换失败时会返回null而非抛出异常,我们可以配合??运算符给空输入/非法输入设置默认值(比如留空时默认按0计算),同时清理原有代码中重复定义的局部变量、重复转换的冗余逻辑。
修改后的计算逻辑代码
final price1 = TextEditingController(); final price2 = TextEditingController(); final price3 = TextEditingController(); final deliveryCharge = TextEditingController(); double total = 0.0; void priceTotal() { // 空值/非法格式默认赋值0.0 double p1 = double.tryParse(price1.text) ?? 0.0; double p2 = double.tryParse(price2.text) ?? 0.0; double p3 = double.tryParse(price3.text) ?? 0.0; double delivery = double.tryParse(deliveryCharge.text) ?? 0.0; setState(() { total = p1 + p2 + p3 + delivery; }); print(total.toString()); }
修改后的点击事件代码
删掉冗余的重复转换逻辑,直接调用计算方法即可:
onPressed: () { priceTotal(); },
可选优化:限制输入框仅能输入数字
从输入源头避免非法字符输入,进一步降低异常概率,需要给所有TextField添加键盘类型和输入过滤配置:
// 注意使用inputFormatters需要先导入 import 'package:flutter/services.dart'; TextField( controller: price3, // 弹出带小数的数字键盘 keyboardType: const TextInputType.numberWithOptions(decimal: true), // 限制仅能输入数字和小数点 inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*'))], decoration: const InputDecoration( // 原有装饰配置保持不变 border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), ), prefixIcon: Padding( padding: EdgeInsets.all(8.0), child: FaIcon( FontAwesomeIcons.rupeeSign, size: 20.0, ), ), hintText: 'Price', ), ),
内容的提问来源于stack exchange,提问作者Dren
相关产品推荐
相关产品推荐

