Flutter非表单场景下为Elevated Button添加输入验证方案
解决方案
不需要Form组件也能实现这个验证逻辑,直接在Calculate按钮的点击事件里添加判断即可,同时可以顺便处理int.parse的潜在异常风险(虽然你已经用了FilteringTextInputFormatter.digitsOnly,但空输入的拦截还是要优先处理)。
修改后的按钮点击逻辑代码:
ElevatedButton( style: ElevatedButton.styleFrom( primary: Theme.of(context).primaryColor, ), onPressed: () { // 先验证输入是否为空(trim处理防止全空格情况) final costText = costController.text.trim(); if (costText.isEmpty) { // 用SnackBar显示提示,轻量且不打断操作流程 ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("请输入车辆成本")), ); return; // 终止后续计算逻辑 } // 验证通过,执行计算 setState(() { toPrint = calc( dropDownValue!, int.parse(costText), ).toString(); }); }, child: const Text("Calculate")),
可选提示方式:AlertDialog
如果你需要更醒目的提示,可以替换为弹窗:
if (costText.isEmpty) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text("提示"), content: const Text("请输入车辆成本"), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text("确定"), ), ], ), ); return; }
内容的提问来源于stack exchange,提问作者Great
相关产品推荐
相关产品推荐

