Validating input using the Form widget

We must add the Form widget to our layout to be capable of validating all the fields at once during saving. This is done by simply wrapping our form field widgets with a Form widget. We also set the key property of our Form with a GlobalKey instance (_formKey in the State object of the following code) so that we can use it later in the save() method:

class RequestFavorPageState extends State<RequestFavorPage> {
final _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
// returns the widget subtree wrapped in a Form. hidden for brevety.
}
}

The save() method looks similar to previous ones:

FlatButton(
child: Text("SAVE"),
textColor: Colors.white,
onPressed: () {
RequestFavorPageState.of(context).save(); // we could call save()
// method directly as we
// are in the same class.
// Intentionally left for
// exemplification.
},
)

It looks up the tree for the corresponding state and asks it to save. The save() method does the hard work:

void save() {
if (_formKey.currentState.validate()) {
// store the favor request on firebase
Navigator.pop(context);
}
}

OK, right now, it does nothing much; it only calls the validation for the corresponding form that walk through all the form fields and validates them, as you already know.

Check the chapter's attached source code files to check the validation code for the form fields.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.15.94