Flutter: Form and validator
In my previous posts, I introduced the MVP architecture pattern and handling the key actions & next focus with the text Fields. Today, I will demonstrate how I use the form and validator in Flutter.
The demonstration will divide into three parts:
Build the basic form
Validate fields
Get datas
Build the basic form
The form has three TextFormFields and RaisedButton so the widget trees as below:

The definition of each widget, you can refer at the Flutter Widgets.
There is the purpose of each widget in BMI form.
- The container contents a child and sets its padding and color.
- The SingleChildScrollerView: “a box in which a single widget can be scrolled” hold the bmi form that can scroll
- The Form “an optional container for grouping together multiple form field widgets”
- The Column “a widget that displays its children in a vertical array”
- The TextFormField “a FormField that contains a TextField”
- The Padding “a widget that insets its child by the given padding”

How does the validator work?
After studying from Flutter IO form validation guideline, there are three steps to handle the validations:
- Create the GlobalKey for BMI form: I declare a variable keyForm as a GlobalKey that is the unique key for a form widget refer at line 1 and 8 of above bmiform.dart file.
- Add the validations to weight, height and age field: I handle at line 23–27, 49 -53 and 73–77 of bmifields.dart file respectively
- Create a button to validate and submit the form: bmifields.dart has been included in the method calculateButton.
After building the UI and handling the form validation, I need to get data for the submit form.
Get data and submit
Each text form field has an action onSave that is triggered by calling onSave from _keyform.
_formKey.currentState.save();
In each onSave action, I store the values and use in the submission action.
Try to calculate without data so I got the error listing as the below image.

Finally, the form has been handling the validation before processing the data.
Inspired by Building a form with validation
Check the source code at BMI calculator
The Flutter Pub is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts etc. about this great technology to teach you how to build beautiful apps with it. You can find us on Facebook, Twitter, and Medium or learn more about us here. We’d love to connect! And if you are a writer interested in writing for us, then you can do so through these guidelines.
