Flutter中if else块遇空输入仍打印结果问题求助
问题分析与解决:输入为空时仍打印控制器文本
我编写了一段用于保存数据前检查输入字段是否为空的if else代码块,但发现即使其中一个输入为空,控制器的文本依然会被打印出来。相关代码如下:
void submitData() async { List<newIngredientList> _ingName = []; for (var textInputWidget in _textInputList) { if (textInputWidget.controller.text.isEmpty || textInputWidget.quantityController.text.isEmpty) { showCupertinoDialog( //message empty field ); } else { _ingName.add(newIngredientList( textInputWidget.controller.text, textInputWidget.quantityController.text, )); print(textInputWidget.controller.text); print(textInputWidget.quantityController.text); } } }
问题原因
- 代码是在循环里逐个检查每个输入控件,如果某个控件为空,只会弹出提示但不会终止循环,后续非空的控件依然会走else分支执行打印逻辑,所以你会看到有文本被打印出来。
- 另外
showCupertinoDialog是异步弹窗,不会阻塞当前代码执行,弹窗出现的同时循环还在继续处理后续控件。
修复方案
方案1:发现空字段后立即终止操作
如果希望只要有一个输入为空就停止所有后续处理,不在执行任何打印或添加操作,可以在弹窗后直接终止函数:
void submitData() async { List<newIngredientList> _ingName = []; for (var textInputWidget in _textInputList) { if (textInputWidget.controller.text.isEmpty || textInputWidget.quantityController.text.isEmpty) { await showCupertinoDialog( context: context, builder: (context) => CupertinoAlertDialog( title: const Text('提示'), content: const Text('存在空字段,请检查'), actions: [ CupertinoDialogAction( child: const Text('确定'), onPressed: () => Navigator.pop(context), ), ], ), ); // 弹窗关闭后直接返回,终止后续所有操作 return; } else { _ingName.add(newIngredientList( textInputWidget.controller.text, textInputWidget.quantityController.text, )); print(textInputWidget.controller.text); print(textInputWidget.quantityController.text); } } // 所有字段验证通过后,执行保存等后续逻辑 }
方案2:先批量检查所有字段
如果想先统一检查所有输入,确认无空字段后再执行添加和打印:
void submitData() async { List<newIngredientList> _ingName = []; // 先检查所有控件是否存在空字段 bool hasEmptyField = _textInputList.any((widget) => widget.controller.text.isEmpty || widget.quantityController.text.isEmpty ); if (hasEmptyField) { await showCupertinoDialog( context: context, builder: (context) => CupertinoAlertDialog( title: const Text('提示'), content: const Text('存在空字段,请检查'), actions: [ CupertinoDialogAction( child: const Text('确定'), onPressed: () => Navigator.pop(context), ), ], ), ); return; } // 所有字段非空,再批量处理 for (var textInputWidget in _textInputList) { _ingName.add(newIngredientList( textInputWidget.controller.text, textInputWidget.quantityController.text, )); print(textInputWidget.controller.text); print(textInputWidget.quantityController.text); } // 执行保存等后续逻辑 }
内容的提问来源于stack exchange,提问作者Giovanni
相关产品推荐
相关产品推荐

