I have a form with multiple controls but spreaded over mulitple tabs. If the user clicks a button I like to call the validator function for a single field.
To validate individual form field create key with FormFieldState
type, assign that key to form field and call validate
method on key's current state:
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
class MyCustomFormState extends State<MyCustomForm> {
final _formFieldKey = GlobalKey<FormFieldState>();
@override
Widget build(BuildContext context) {
return Form(
child: Column(children: <Widget>[
TextFormField(
key: _formFieldKey,
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
RaisedButton(
onPressed: () {
if (_formFieldKey.currentState.validate()) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
},
child: Text('Submit'),
),
]));
}
}
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