Flutter - 当TextField失去焦点时,如何验证TextFormField

6

我有一个关于验证文本表单字段的问题。

是否有一种方法可以在TextFormField失去焦点时仅验证其值?

当焦点改变时,我想调用API检查用户名是否已存在于我的数据库中。如果我将autoValidate设置为true,那么每次用户按键时都会进行验证。因此,如果一个用户名有20个字符,它将调用我的API 20次。因此为了减少开销,我只想在焦点改变时调用API。

2个回答

17

您可以将 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;
   },
 )  

非常感谢你 Ayush!!! 它完美地工作了!我真的非常感激!!!!谢谢 :) - pascal22
你可以接受我的答案,以帮助其他人轻松找到解决方案。 - Ayush Bherwani
1
抱歉让你等了这么久,我接受你的答案,谢谢。 - pascal22

2

我没有找到任何捷径。但是我已经编写了以下代码,它对我有效。

  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...
                }
              },
            )
          ],
        ),
      ),
    );
  }

学习这种方法对我来说非常有效。 - Leland Reardon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接