我正在制作一个定制的TextFormField Widget,它将被多次使用。如何在不验证同一列表/行/列中的任何其他TextFormField的情况下验证单个TextFormField。
Widget timeTextField (TextEditingController controller){
return TextFormField(
controller: controller,
validator: (String userInput){
if(userInput.isEmpty){return 'Need to input time';}
},
onFieldSubmitted: (String userInput){
setState(() {
debugPrint(userInput);
controller.text = "amout";
debugPrint(controller.text);
});
},
);
}当用户按下键盘上的submit时,它将进行验证,如果TextFormField为空,则只向用户按下submit的TextFormField发送验证错误。
发布于 2019-06-13 09:31:15
TextField中的验证是基于放置在其中的Form (而不是Column、Row或List)进行的。要验证TextFields,分别将它们放在不同的表单中,分配不同的键并分别调用_formKey.currentState.validate。
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _form1Key = GlobalKey();
final GlobalKey<FormState> _form2Key = GlobalKey();
final GlobalKey<FormState> _form3Key = GlobalKey();
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Form(
key: _form1Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form2Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form3Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
_form2Key.currentState.validate();
}),
);
}
}发布于 2021-02-01 15:09:03
关于一个封闭问题的信息:
您可以使用autovalidateMode。
目前有3种模式。我们以前有折旧的autovalidate。这只适用于FormFields和内部表单。
示例
TextFormField(
autocorrect: false,
autovalidateMode: AutovalidateMode.onUserInteraction,
cursorColor: Colors.black,
key: _usernameKey,参考
https://stackoverflow.com/questions/56571864
复制相似问题