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);
}
                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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With