Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous validation with Flutter Form

Tags:

flutter

I'm new in Flutter. In my app I need option for checking username already exist or not asynchronously from database when user typed and focus out from text box.

The validator require String return type that's why I can not add Future<String>

How can I do like as below with Flutter TextFormField? or any process that full fill my requirement.

validator: myValidator
Future myValidator(String username) async{
    return await checkUser(username);
}
like image 824
Akash khan Avatar asked Sep 11 '25 04:09

Akash khan


1 Answers

Note: Currently Flutter doesn't support the async function in validator. You can do it in a tricky way.

Define these variables

dynamic _validationMsg;
final _usernameCtrl = TextEditingController();

Your async validator function (with modification)

Future myValidator(String username) async{
    _validationMsg = null;
    setState(() {});

    bool isExist = await checkUser(username);
    
    if(isExist){
      _validationMsg = "${username} already taken";
      setState(() {});
    }
}

Now add the TextFormField widget wrapped with a Focus widget.

Focus(
  child: TextFormField(
    controller: _usernameCtrl,
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: (val) => _validationMsg,
  ),
  onFocusChange: (hasFocus) {
    if (!hasFocus) myValidator(_usernameCtrl.text);
  }
)

Code Ref: https://flutter-tutorial.com/flutter-async-validation

like image 141
Harun Avatar answered Sep 14 '25 01:09

Harun