[英]Flutter - Validate TextFormField only When TextField lost focus
I have a question about validating the text form field.我有一个关于验证文本表单字段的问题。
Is there a way to only validate the value of a TextFormField
only when it lost focus?有没有办法只在失去焦点时才验证TextFormField
的值?
I want to call an API to check if the username already exists in my database when the focus is changed.我想调用一个 API 来检查当焦点改变时用户名是否已经存在于我的数据库中。 If I set autoValidate
in TextFormField
true it will validate every time the user press a key.如果我在TextFormField
设置autoValidate
为 true,它会在用户每次按下一个键时进行验证。 So if a username has 20 characters it will call my API 20 times.因此,如果用户名有 20 个字符,它将调用我的 API 20 次。 Hence to remove overhead I want to call API only when the focus is changed.因此,为了消除开销,我只想在焦点改变时调用 API。
You can attach a focusNode to TextField
so whenever focus changes you can make an api call and validate the text.您可以将 focusNode 附加到TextField
以便每当焦点更改时,您都可以进行 api 调用并验证文本。 Inside your class try this在你的课堂上试试这个
FocusNode focusNode;
bool _hasInputError;
String text;
@override
void initState() {
super.initState();
focusNode = new FocusNode();
focusNode.addListener(() {
if (!focusNode.hasFocus) {
setState(() {
_hasInputErro = //Check your conditions on text variable
});
}
});
}
And in TextField
do this并在TextField
执行此操作
TextField(
focusNode: _focusNode,
decoration: InputDecoration(
errorText: _hasInputError ? "Your error message" : null,
),
onChanged: (String _text) {
text = _text;
},
)
I have not found any shortcut way.我还没有找到任何捷径。 But I have made a code as follow which is working for me.但是我已经制作了如下代码,它对我有用。
final formKey = GlobalKey<FormState>();
FocusNode textFieldFocusNode = FocusNode();
bool canCleartextFieldError = false;
@override
void initState() {
super.initState();
addListener();
}
addListener(){
textFieldFocusNode.addListener(() {
setState(() {
canCleartextFieldError = textFieldFocusNode.hasFocus;
});
});
}
@override
Widget build(BuildContext context) {
return Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: formKey,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
TextFormField(
focusNode: textFieldFocusNode,
validator: (text) {
return canCleartextFieldError == true? null: text == ''? 'please enter text here...': null;
},
),
FlatButton(
child: Text('Button'),
onPressed: () {
setState(() { canCleartextFieldError = false; });
if(formKey.currentState.validate()){
// Todo: do your valid job here...
}
},
)
],
),
),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.