我有一个关于验证文本表单字段的问题。
是否有一种方法可以在TextFormField
失去焦点时仅验证其值?
当焦点改变时,我想调用API检查用户名是否已存在于我的数据库中。如果我将autoValidate
设置为true
,那么每次用户按键时都会进行验证。因此,如果一个用户名有20个字符,它将调用我的API 20次。因此为了减少开销,我只想在焦点改变时调用API。
您可以将 focusNode 附加到 TextField
,以便在焦点更改时进行 API 调用并验证文本。在您的类中尝试以下内容:
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
});
}
});
}
在TextField
中进行如下操作
TextField(
focusNode: _focusNode,
decoration: InputDecoration(
errorText: _hasInputError ? "Your error message" : null,
),
onChanged: (String _text) {
text = _text;
},
)
我没有找到任何捷径。但是我已经编写了以下代码,它对我有效。
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...
}
},
)
],
),
),
);
}