Form Builder in Flutter - Form Validation

In this Post we are going to learn how handle the form validation in flutter.
To handle the form validation in flutter we are going to use flutter_form_builder plugin

Flutter Form Builder

Flutter Form Builder

 

Let's start
pubspc.yaml file
add  flutter_form_builder: ^3.7.1 plugin pubspec.yaml file under dependencies
dependencies:
  flutter_form_builder: ^3.7.1

 

import  'package:flutter_form_builder/flutter_form_builder.dart'; in dart file

 

List of Form widgets

FormBuilderTextField – Text input, it accepts input of single-line text, multi-line text, password, email, urls etc by using different configurations and validators
FormBuilderCheckbox – Single Checkbox field

FormBuilderCheckboxList – List of Checkboxes for multiple selection

FormBuilderChipsInput – Takes a list of Chips as input

FormBuilderDateTimePicker – For Date, Time and DateTime input

FormBuilderDropdown – Used to select one value from a list as a Dropdown

FormBuilderRadio – Used to select one value from a list of Radio Widgets

FormBuilderRangeSlider – Used to select a range from a range of values

FormBuilderRate – For selection of a numerical value as a rating

FormBuilderSegmentedControl – For selection of a value from the CupertinoSegmentedControl as an input

FormBuilderSignaturePad – Presents a drawing pad on which user can doodle

FormBuilderSlider – For selection of a numerical value on a slider

FormBuilderStepper – Selection of a number by tapping on a plus or minus symbol

FormBuilderSwitch – On/Off switch

FormBuilderTypeAhead – Auto-completes user input from a list of items
Check the code
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        textTheme: TextTheme(
          body1: TextStyle(fontSize: 18),
          display1: TextStyle(fontSize: 1),


        ),
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
  var data;
  bool autoValidate = true;
  bool readOnly = false;
  bool showSegmentedControl = true;
  final GlobalKey _fbKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Form Validation"),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: SingleChildScrollView(
          child: Column(
            children: [
              FormBuilder(
                key: _fbKey,
                initialValue: {
                  'date': DateTime.now(),
                  'accept_terms': false,
                },
                autovalidate: true,
                child: Column(
                  children: [
                    FormBuilderTextField(
                      attribute: 'text',
                      style: Theme.of(context).textTheme.body1,
                      validators: [FormBuilderValidators.required()],
                      decoration: InputDecoration(labelText: "Full Name"),
                    ),
                    FormBuilderDateTimePicker(
                      attribute: "date",
                      style: Theme.of(context).textTheme.body1,
                      inputType: InputType.date,
                      validators: [FormBuilderValidators.required()],
                      format: DateFormat("dd-MM-yyyy"),
                      decoration: InputDecoration(labelText: "Date of Birth"),
                    ),
                    FormBuilderDropdown(
                      attribute: "gender",
                      style: Theme.of(context).textTheme.body1,
                      decoration: InputDecoration(labelText: "Gender"),
                      // initialValue: 'Male',
                      hint: Text('Select Gender'),
                      validators: [FormBuilderValidators.required()],
                      items: ['Male', 'Female', 'Other']
                          .map((gender) => DropdownMenuItem(
                          value: gender, child: Text("$gender")))
                          .toList(),
                    ),
                    FormBuilderTextField(
                      attribute: "age",
                      style: Theme.of(context).textTheme.body1,
                      decoration: InputDecoration(labelText: "Age"),
                      keyboardType: TextInputType.number,
                      validators: [
                        FormBuilderValidators.numeric(),
                        FormBuilderValidators.max(70),
                      ],
                    ),
                    FormBuilderSlider(
                      attribute: "slider",
                      validators: [FormBuilderValidators.min(6)],
                      min: 0.0,
                      max: 20.0,
                      initialValue: 1.0,
                      divisions: 20,
                      decoration: InputDecoration(
                        labelStyle:   Theme.of(context).textTheme.body1,
                          labelText: "Income in Lacs"),
                    ),
                    FormBuilderSegmentedControl(
                      decoration: InputDecoration(labelText: "No of Children",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "movie_rating",

                      options: List.generate(5, (i) => i + 1)
                          .map(
                              (number) => FormBuilderFieldOption(value: number))
                          .toList(),
                    ),
                    FormBuilderStepper(
                      decoration: InputDecoration(labelText: "No of Houses",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "stepper",
                      initialValue: 10,
                      step: 1,
                    ),
                    FormBuilderCheckboxList(
                      decoration:
                      InputDecoration(labelText: "Known Langugaes",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "languages",
                      initialValue: ["English"],
                      options: [
                        FormBuilderFieldOption(value: "English"),
                        FormBuilderFieldOption(value: "Hindi"),
                        FormBuilderFieldOption(value: "Telugu"),
                        FormBuilderFieldOption(value: "Other")
                      ],
                    ),
                    FormBuilderSignaturePad(
                      decoration: InputDecoration(labelText: "Signature",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "signature",
                      height: 100,
                    ),
                    FormBuilderRate(
                      decoration: InputDecoration(labelText: "Rate your Company",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "rate",
                      iconSize: 32.0,
                      initialValue: 1,
                      max: 5,
                    ),
                    FormBuilderCheckbox(
                      attribute: 'accept_terms',
                      label: Text(
                          "I have read and agree to the terms and conditions",),
                      validators: [
                        FormBuilderValidators.requiredTrue(
                          errorText:
                          "You must accept terms and conditions to continue",
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  MaterialButton(
                    child: Text("Submit",style: TextStyle(color: Colors.white),),
                    color: Colors.green,
                    onPressed: () {
                      _fbKey.currentState.save();
                      if (_fbKey.currentState.validate()) {
                        print(_fbKey.currentState.value);
                      }
                    },
                  ),
                  MaterialButton(
                    child: Text("Reset",style: TextStyle(color: Colors.white),),
                    color: Colors.deepOrange,
                    onPressed: () {
                      _fbKey.currentState.reset();
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}