简体   繁体   中英

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?

I want to call an API to check if the username already exists in my database when the focus is changed. If I set autoValidate in TextFormField true it will validate every time the user press a key. So if a username has 20 characters it will call my API 20 times. Hence to remove overhead I want to call API only when the focus is changed.

You can attach a focusNode to TextField so whenever focus changes you can make an api call and validate the text. 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(
  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...
                }
              },
            )
          ],
        ),
      ),
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM