Section 3: Flutter Form Validation
Forms in Flutter can be used to collect user data. This is a continuation of this tutorial, so you can refer to it to proceed well.
In your screens* folder, create a new file and call it form_ex.dart. Add the following code:
Notice between lines 11–25, we have added code in our state to handle form state. In the _submit function, we have a Boolean variable created called isValid that changes to false and throws an error if the data submitted is not correct, based on the conditions we will put in the submit button. We also have a validator attribute in each field to check whether the field is empty, and for email, to check whether the email is valid.
To add navigation to *intro.dart, we shall duplicate the Inkwell and navigate as follows; (we have redundant data that we shall fix later)
This will give you the following UI:
Once the submit button is clicked, if the validator throws an error, the submit function will turn isValid to false and prevent the submission. Otherwise, it will proceed well. This is an example of ensuring users collect valid data.
Notice that this is redundant data in intro.dart. To prevent this, we shall learn about custom widgets in the next tutorial.