Form Builder in Flutter - Form Validation | RRTutors

Last updated Dec 07, 2020
In this Post we are going to learn how handle the form validation in flutter.
In any application validating the Forms is mandatory, like validating the Email, validating the button events, validating the Password text...

To handle the form validation in flutter we are going to use flutter_form_builder plugin

 

Flutter provides us with a Form widget. We can build up our child of the widget how we want and just add TextFormField widgets to make it apart of the form. Any TextFormField in the Form child widget will become a field in the Form that we can work with. 

 

This library contains different Form widgets like TextFormField,Button ...

Check simple Form Widget syntax with TextFiledValidation

 

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: ^4.0.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(



        ),
        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  _fbKey = GlobalKey<FormBuilderState>();
  @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,
                },
                autovalidateMode: AutovalidateMode.always,
                child: Column(
                  children: [
                    FormBuilderTextField(
                      name: 'text',
                      style: Theme.of(context).textTheme.body1,
                      validator: FormBuilderValidators.compose([FormBuilderValidators.required(context)]),
                      decoration: InputDecoration(labelText: "Full Name"),
                    ),
                    FormBuilderDateTimePicker(
                      name: "date",
                      style: Theme.of(context).textTheme.body1,
                      inputType: InputType.date,
                      validator: FormBuilderValidators.compose([FormBuilderValidators.required(context)]),
                      format: DateFormat("dd-MM-yyyy"),
                      decoration: InputDecoration(labelText: "Date of Birth"),
                    ),
                    FormBuilderDropdown(
                      name: "gender",
                      style: Theme.of(context).textTheme.body1,
                      decoration: InputDecoration(labelText: "Gender"),
                      // initialValue: 'Male',
                      hint: Text('Select Gender'),
                      validator: FormBuilderValidators.compose([FormBuilderValidators.required(context)]),
                      items: ['Male', 'Female', 'Other']
                          .map((gender) => DropdownMenuItem(
                          value: gender, child: Text("$gender")))
                          .toList(),
                    ),
                    FormBuilderTextField(
                      name: "age",
                      style: Theme.of(context).textTheme.body1,
                      decoration: InputDecoration(labelText: "Age"),
                      keyboardType: TextInputType.number,
                      validator:FormBuilderValidators.compose( [
                        FormBuilderValidators.numeric(context),
                        FormBuilderValidators.max(context,70),
                      ]),
                    ),
                    FormBuilderSlider(
                      name: "slider",
                      validator: FormBuilderValidators.compose([
                        FormBuilderValidators.min(context, 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,),
                      name: "movie_rating",

                      options: List.generate(5, (i) => i + 1)
                          .map(
                              (number) => FormBuilderFieldOption(value: number))
                          .toList(),
                    ),
                    FormBuilderTouchSpin(
                      decoration: InputDecoration(labelText: 'Stepper'),
                      name: 'stepper',
                      initialValue: 10,
                      step: 1,
                      iconSize: 48.0,
                      addIcon: Icon(Icons.arrow_right),
                      subtractIcon: Icon(Icons.arrow_left),
                    ),
                 /*   FormBuilderStepper(
                      decoration: InputDecoration(labelText: "No of Houses",labelStyle: Theme.of(context).textTheme.body1,),
                      attribute: "stepper",
                      initialValue: 10,
                      step: 1,
                    ),*/

                    FormBuilderCheckboxGroup (
                      decoration:
                      InputDecoration(labelText: "Known Langugaes",labelStyle: Theme.of(context).textTheme.body1,),
                      name: "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,),
                      name: "signature",
                      height: 100,
                    ),
                    FormBuilderRating(
                      decoration: InputDecoration(labelText: "Rate your Company",labelStyle: Theme.of(context).textTheme.body1,),
                      name: "rate",
                      iconSize: 32.0,
                      initialValue: 1,
                      max: 5,
                    ),
                    FormBuilderCheckbox(
                      name: 'accept_terms',
                      title: Text(
                        "I have read and agree to the terms and conditions",),
                      validator: FormBuilderValidators.compose([
                        FormBuilderValidators. required(
                          context,
                          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();
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

 

Dynamic Expansion Listivew - Flutter

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

9266 Views