[英]TextFormField validation when focus changes
I am using a form and some TextFormFields.我正在使用一个表单和一些 TextFormFields。 I can validate the user input as below:
我可以验证用户输入如下:
final _form = GlobalKey<FormState>();
void saveForm(){
_form.currentState.validate()
}
//saveForm runs when a save button is pressed.
I want to know whether it's possible to run validate function for a TextField when it loses its focus or not.(I don't want to validate the input by clicking a button and instead, I want to run validate function when user changes the TextField.)我想知道是否可以在 TextField 失去焦点时对其运行 validate function。(我不想通过单击按钮来验证输入,而是在用户更改 TextField 时运行 validate function .)
I think you just want to add autovalidate: true,
in your form so when your focus is change validation is call我认为您只想在表单中添加
autovalidate: true,
因此当您的焦点是更改验证时调用
Form(
key: _formKey,
autovalidate: true,
child:/*...*/
)
Create your form like创建您的表单,例如
var _formKey = GlobalKey<FormState>();
bool _autoValidate = false;
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidate: _autoValidate,
child: /* ... */
),
),
);
}
when you click on save当你点击保存
void _onSignUpClicked(BuildContext context) {
if (_formKey.currentState.validate()) {
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Successfully sign up")));
} else {
setState(() {
_autoValidate = true;
});
}
}
Put TextEditingController
to TextField
and use addListener
for getting every change.将
TextEditingController
放入TextField
并使用addListener
来获取每个更改。 And do validate process inside that listener.并在该侦听器内验证过程。
To notice, the accepted solution now is deprecated after 1.19
需要注意的是,现在接受的解决方案在
1.19
之后已弃用
Now, new parameters has been introduced AutovalidateMode
with three essential constants:现在,引入了具有三个基本常量的新参数
AutovalidateMode
:
Add autoValidateMode to your form将 autoValidateMode 添加到您的表单
autovalidateMode: AutovalidateMode.onUserInteraction,
autovalidateMode:AutovalidateMode.onUserInteraction,
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column()
)
Auto validate has two more modes disabled (never auto validate) and always (in all cases even without any user interaction).自动验证有另外两种禁用模式(从不自动验证)和始终(在所有情况下,即使没有任何用户交互)。
Read more over here在这里阅读更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.