I am using a form and some TextFormFields. I can validate the user input as below:
final _form = GlobalKey<FormState>();
void saveForm(){
_form.currentState.validate()
}
//saveForm runs when a save button is pressed.
I want to know whether it's possible to run validate function for a TextField when it loses its focus or not.(I don't want to validate the input by clicking a button and instead, I want to run validate function when user changes the TextField.)
To validate a text field when focus changes from one field to the next, you need a FocusNode to detect when focus has been removed and a GlobalKey<FormFieldState> on the TextFormField to tell it to validate. Here is a sample: Thanks for contributing an answer to Stack Overflow!
In Flutter, the user can shift the focus between multiple TextFormFields inside a Form by using the soft keyboard (not by tapping the TextFormFields). This article shows you 2 ways to do so.
Validating TextFormField 1 1.Create a Form with a global key.#N#final _formKey = GlobalKey<FormState> (); ... body: Center ( child: Form ( key:... 2 Add a FormField with validation logic#N#TextFormField ( ..... validator: (value) { if (value.isEmpty) { return... 3 Create a button to validate and submit of the Form More ...
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
I think you just want to add autovalidate: true,
in your form so when your focus is change validation is call
Form(
key: _formKey,
autovalidate: true,
child:/*...*/
)
Create your form like
var _formKey = GlobalKey<FormState>();
bool _autoValidate = false;
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidate: _autoValidate,
child: /* ... */
),
),
);
}
when you click on save
void _onSignUpClicked(BuildContext context) {
if (_formKey.currentState.validate()) {
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Successfully sign up")));
} else {
setState(() {
_autoValidate = true;
});
}
}
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