4

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);
}
Akash khan
  • 861
  • 13
  • 25
  • Check my answer posted [here](https://stackoverflow.com/a/75685423/11217849). Maybe it will help you. – petomuro Mar 09 '23 at 19:10

2 Answers2

5

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

Harun
  • 1,137
  • 1
  • 9
  • 7
-2

Can you try something like this:

validator: (username) async {
  String result = await checkUser(username);
  return result;  
} 
NelsonThiago
  • 802
  • 7
  • 12