Flutter Forms
Forms are the most important part of all mobile and web applications.Form is used to get information from the user who interacts with the application. We can use these for different reasons, which depend on the business and logic requirements, such as authenticating the user, adding a user, etc. A form can contain many widgets like text fields, buttons, checkboxes, radio buttons, etc.
Creating Form
We can use Form widget to create a form. The form widget acts as a container, which helps us in grouping and validating the multiple form fields. When we create a form, it is necessary for providing a GlobalKey. This key help uniquely identifies the form and allows us to validate in the form fields.
The form widget uses TextFormField widgetto provide the users a way to enter the text.
Let us create a form. In this code snippet, we have created a custom class named MyCustomForm. Inside this class, we have defined a global key as _formKey. This key holds the FormState and can be retrieved by the form widget. Inside the build method, we have to add some custom styles and use the TextFormField widget to get data from the fields name, phone number, date of birth, or just a normal field. Inside the TextFormField, we used InputDecoration that helps us with the look and feel of the form properties such as borders, labels, icons, hint, styles, etc. Finally, we have added a submit button to the form.
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'Flutter Form Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: Text(appTitle), ), body: MyCustomForm(), ), ); } } // Create a Form widget. class MyCustomForm extends StatefulWidget { @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class. This class contains the form. class MyCustomFormState extends State{ // We have Created a global key that uniquely identifies the Form widget // which allows validation of the form also. final _formKey = GlobalKey (); @override Widget build(BuildContext context) { // Adding the _formKey created above to the form as a key. return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.person), hintText: 'Enter your name', labelText: 'Name', ), ), TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.phone), hintText: 'Enter a phone number', labelText: 'Phone', ), ), TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.calendar_today), hintText: 'Enter your date of birth', labelText: 'Dob', ), ), new Container( padding: const EdgeInsets.only(left: 150.0, top: 40.0), child: new RaisedButton( child: const Text('Submit'), onPressed: null, )), ], ), ); } }
Output
This form made from the code contains three fields: name, phone number and date of birth, and a submit button.
Form validation
Validation allows us to check or confirm a standard for the input we get from the user. It helps us authenticate the entered data.
Validation is a common practice in all current digital interactions. To validate a form, we need to implement these steps.
Step 1: Add a global key to the Form.
Step 2: Use TextFormField validator property to validate the input.
Step 3: Create a submit button to validate and submit the form’s fields and display the errors.
Let us understand it with an example. In the below code, we used the validator() function in the TextFormField to validate the input. If the user inputs the wrong input, the validator function returns an error message; otherwise, it returns a null. It returns an error message when the text field is empty.
The validator() function can be written as below code snippets:
validator: (value) { if (value.isEmpty) { return 'Please enter some text'; } return null; },
Now, add the validator() function in the TextFormField widget. Replace the following code with the main.dart file.
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'Flutter Form Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: Text(appTitle), ), body: MyCustomForm(), ), ); } } // Create a Form widget. class MyCustomForm extends StatefulWidget { @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class, which holds data related to the form. class MyCustomFormState extends State{ // Create a global key that uniquely identifies the Form widget // and allows validation of the form. final _formKey = GlobalKey (); @override Widget build(BuildContext context) { // Build a Form widget using the _formKey created above. return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.person), hintText: 'Enter your full name', labelText: 'Name', ), validator: (value) { if (value.isEmpty) { return 'Please enter some text'; } return null; }, ), TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.phone), hintText: 'Enter a phone number', labelText: 'Phone', ), validator: (value) { if (value.isEmpty) { return 'Please enter valid phone number'; } return null; }, ), TextFormField( decoration: const InputDecoration( icon: const Icon(Icons.calendar_today), hintText: 'Enter your date of birth', labelText: 'Dob', ), validator: (value) { if (value.isEmpty) { return 'Please enter valid date'; } return null; }, ), new Container( padding: const EdgeInsets.only(left: 150.0, top: 40.0), child: new RaisedButton( child: const Text('Submit'), onPressed: () { // It returns true if the form is valid, otherwise returns false if (_formKey.currentState.validate()) { // If the form is valid, display a Snackbar. Scaffold.of(context) .showSnackBar(SnackBar(content: Text('Data is in processing.'))); } }, )), ], ), ); } }
Output
Now, run the app. The following screen appears.
In this form, if you left any input field blank, you will get an error message like below screen.