Reputation: 979
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);
}
Upvotes: 4
Views: 1402
Reputation: 1237
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
Upvotes: 7
Reputation: 830
Can you try something like this:
validator: (username) async {
String result = await checkUser(username);
return result;
}
Upvotes: -3