Form Validation In Flutter

Introduction

 
In this article, we will learn how to apply form validation in Flutter. For form validation, we will use flutter_form_builder which provides us syntactic sugar for creating a form widget and reduces the need of boilerplate to build a form, validate fields, react to changes, and collect the value of the form in the form of a map. So, let’s begin to implement form validation in Flutter.
 

Output

 
Form Validation In Flutter
Plugin Required: flutter_form_builder: ^3.4.1
 

Programming Steps

 
Step 1
 
The first and most basic step is to create a new application in Flutter. If you are a beginner in Flutter, then you can check my blog Create a first app in Flutter. I have created an app named as “flutter_form_validation”.
 
Step 2
 
We need to add a form builder plugin which provides us form validation. For that, open the pubspec.yaml file in your project and add the following dependencies into it. 
  1. dependencies:  
  2.  flutter:  
  3.    sdk: flutter  
  4.  cupertino_icons: ^0.1.2  
  5.  flutter_form_builder: ^3.4.1  
Step 3
 
Now, go to main.dart and import form builder package.
  1. import 'package:flutter_form_builder/flutter_form_builder.dart';  
Step 4
 
Now, we will implement all types of form validation controllers to understand how to apply validation to form controllers. Following is the programatically implementation for that.
  1. import 'package:flutter/material.dart';    
  2. import 'package:flutter_form_builder/flutter_form_builder.dart';    
  3. import 'package:intl/intl.dart';    
  4.      
  5. void main() => runApp(MyApp());    
  6.      
  7. class MyApp extends StatelessWidget {    
  8.  @override    
  9.  Widget build(BuildContext context) {    
  10.    return MaterialApp(    
  11.      theme: ThemeData(    
  12.        primarySwatch: Colors.purple,    
  13.      ),    
  14.      home: MyHomePage(),    
  15.    );    
  16.  }    
  17. }    
  18.      
  19. class MyHomePage extends StatefulWidget {    
  20.  @override    
  21.  _MyHomePageState createState() => _MyHomePageState();    
  22. }    
  23.      
  24. class _MyHomePageState extends State<MyHomePage> {    
  25.  var data;    
  26.  bool autoValidate = true;    
  27.  bool readOnly = false;    
  28.  bool showSegmentedControl = true;    
  29.  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();    
  30.      
  31.  @override    
  32.  Widget build(BuildContext context) {    
  33.    return Scaffold(    
  34.      appBar: AppBar(    
  35.        title: Text("Flutter Form Validation"),    
  36.      ),    
  37.      body: Padding(    
  38.        padding: EdgeInsets.all(10),    
  39.        child: SingleChildScrollView(    
  40.          child: Column(    
  41.            children: <Widget>[    
  42.              FormBuilder(    
  43.                key: _fbKey,    
  44.                initialValue: {    
  45.                  'date': DateTime.now(),    
  46.                  'accept_terms'false,    
  47.                },    
  48.                autovalidate: true,    
  49.                child: Column(    
  50.                  children: <Widget>[    
  51.                    FormBuilderTextField(    
  52.                      attribute: 'text',    
  53.                      validators: [FormBuilderValidators.required()],    
  54.                      decoration: InputDecoration(labelText: "Full Name"),    
  55.                    ),    
  56.                    FormBuilderDateTimePicker(    
  57.                      attribute: "date",    
  58.                      inputType: InputType.date,    
  59.                      validators: [FormBuilderValidators.required()],    
  60.                      format: DateFormat("dd-MM-yyyy"),    
  61.                      decoration: InputDecoration(labelText: "Date of Birth"),    
  62.                    ),    
  63.                    FormBuilderDropdown(    
  64.                      attribute: "gender",    
  65.                      decoration: InputDecoration(labelText: "Gender"),    
  66.                      // initialValue: 'Male',    
  67.                      hint: Text('Select Gender'),    
  68.                      validators: [FormBuilderValidators.required()],    
  69.                      items: ['Male''Female''Other']    
  70.                          .map((gender) => DropdownMenuItem(    
  71.                              value: gender, child: Text("$gender")))    
  72.                          .toList(),    
  73.                    ),    
  74.                    FormBuilderTextField(    
  75.                      attribute: "age",    
  76.                      decoration: InputDecoration(labelText: "Age"),    
  77.                      keyboardType: TextInputType.number,    
  78.                      validators: [    
  79.                        FormBuilderValidators.numeric(),    
  80.                        FormBuilderValidators.max(70),    
  81.                      ],    
  82.                    ),    
  83.                    FormBuilderSlider(    
  84.                      attribute: "slider",    
  85.                      validators: [FormBuilderValidators.min(6)],    
  86.                      min: 0.0,    
  87.                      max: 10.0,    
  88.                      initialValue: 1.0,    
  89.                      divisions: 20,    
  90.                      decoration: InputDecoration(    
  91.                          labelText: "Number of Family Members"),    
  92.                    ),    
  93.                    FormBuilderSegmentedControl(    
  94.                      decoration: InputDecoration(labelText: "Rating"),    
  95.                      attribute: "movie_rating",    
  96.                      options: List.generate(5, (i) => i + 1)    
  97.                          .map(    
  98.                              (number) => FormBuilderFieldOption(value: number))    
  99.                          .toList(),    
  100.                    ),    
  101.                    FormBuilderStepper(    
  102.                      decoration: InputDecoration(labelText: "Stepper"),    
  103.                      attribute: "stepper",    
  104.                      initialValue: 10,    
  105.                      step: 1,    
  106.                    ),    
  107.                    FormBuilderCheckboxList(    
  108.                      decoration:    
  109.                          InputDecoration(labelText: "Languages you know"),    
  110.                      attribute: "languages",    
  111.                      initialValue: ["English"],    
  112.                      options: [    
  113.                        FormBuilderFieldOption(value: "English"),    
  114.                        FormBuilderFieldOption(value: "Hindi"),    
  115.                        FormBuilderFieldOption(value: "Other")    
  116.                      ],    
  117.                    ),    
  118.                    FormBuilderSignaturePad(    
  119.                      decoration: InputDecoration(labelText: "Signature"),    
  120.                      attribute: "signature",    
  121.                      height: 100,    
  122.                    ),    
  123.                    FormBuilderRate(    
  124.                      decoration: InputDecoration(labelText: "Rate this site"),    
  125.                      attribute: "rate",    
  126.                      iconSize: 32.0,    
  127.                      initialValue: 1,    
  128.                      max: 5,    
  129.                    ),    
  130.                    FormBuilderCheckbox(    
  131.                      attribute: 'accept_terms',    
  132.                      label: Text(    
  133.                          "I have read and agree to the terms and conditions"),    
  134.                      validators: [    
  135.                        FormBuilderValidators.requiredTrue(    
  136.                          errorText:    
  137.                              "You must accept terms and conditions to continue",    
  138.                        ),    
  139.                      ],    
  140.                    ),    
  141.                  ],    
  142.                ),    
  143.              ),    
  144.              Row(    
  145.                children: <Widget>[    
  146.                  MaterialButton(    
  147.                    child: Text("Submit"),    
  148.                    onPressed: () {    
  149.                      _fbKey.currentState.save();    
  150.                      if (_fbKey.currentState.validate()) {    
  151.                        print(_fbKey.currentState.value);    
  152.                      }    
  153.                    },    
  154.                  ),    
  155.                  MaterialButton(    
  156.                    child: Text("Reset"),    
  157.                    onPressed: () {    
  158.                      _fbKey.currentState.reset();    
  159.                    },    
  160.                  ),    
  161.                ],    
  162.              )    
  163.            ],    
  164.          ),    
  165.        ),    
  166.      ),    
  167.    );    
  168.  }    
  169. }    
Step 5
 
Great, you are done with form validation in Flutter. Run this project in device or emulator and check the output.
 

Conclusion

 
In this article, we have learned how to implement form validation in Flutter. You can check out more validation in the plugin's official documentation.
 
Reference
Author
Parth Patel
271 7k 1.6m
Next » Chat App In Flutter Using Google Firebase