How To Add From Validation Using Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 05-11-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

How To Add From Validation Using Flutter Android App

From Validation
Step 1:  
We cannot directly remove the time stamp from From Validatiobut using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code

dependencies:
  flutter:
    sdk: flutter
  flutter_form_builder: ^3.7.1
 

Step 2: After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command. 

flutter pub get

Step 3: Open your project’s main.dart file and import material.dart and flutter_form_builder: ^3.7.1. dart package.
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';

Complete Code For From Validation In Flutter
main.dart
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(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        textTheme: TextTheme(
          body1: TextStyle(fontSize: 16,color: Colors.black45,fontWeight: FontWeight.bold),
          display1: TextStyle(fontSize: 10),
        ),
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var data;
  bool autoValidate = true;
  bool readOnly = false;
  bool showSegmentedControl = true;
  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue[800],
        title: Text("Flutter Form Validation"),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              FormBuilder(
                key: _fbKey,
                initialValue: {
                  'date': DateTime.now(),
                  'accept_terms': false,
                },
//                autovalidateMode: true,
                child: Column(
                  children: <Widget>[
                    FormBuilderTextField(
                      attribute: 'text',
                      validators: [FormBuilderValidators.required()],
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.black26),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        contentPadding: EdgeInsets.all(4),
                          labelText: "  Full Name",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                    ),
                    SizedBox(height: 10),
                    FormBuilderDateTimePicker(
                      attribute: "date",
                      inputType: InputType.date,
                      validators: [FormBuilderValidators.required()],
                      format: DateFormat("dd-MM-yyyy"),
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.black26),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        contentPadding: EdgeInsets.all(4),
                          labelText: " Date of Birth",
                        labelStyle:    Theme.of(context).textTheme.body1,
                      ),
                    ),
                    SizedBox(height: 10),
                    FormBuilderDropdown(
                      attribute: " gender",
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.black26),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        contentPadding: EdgeInsets.all(4),
                          labelText: " Gender",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      // initialValue: 'Male',
                      hint: Text(' Select Gender'),
                      validators: [FormBuilderValidators.required()],
                      items: ['Male', 'Female', 'Other']
                          .map((gender) => DropdownMenuItem(
                          value: gender, child: Text("$gender")))
                          .toList(),
                    ),
                    SizedBox(height: 10),
                    FormBuilderTextField(
                      attribute: " age",
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.black26),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        contentPadding: EdgeInsets.all(4),
                          labelText: "Age",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      keyboardType: TextInputType.number,
                      validators: [
                        FormBuilderValidators.numeric(),
                        FormBuilderValidators.max(70),
                      ],
                    ),
                    SizedBox(height: 10),
                    FormBuilderSlider(
                      attribute: "slider",
                      validators: [FormBuilderValidators.min(6)],
                      min: 0.0,
                      max: 10.0,
                      activeColor: Colors.blue[800],
                      initialValue: 1.0,
                      divisions: 20,
                      decoration: InputDecoration(
                          labelText: "Number of Family Members",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                    ),
                    SizedBox(height: 10),
                    FormBuilderSegmentedControl(
                      decoration: InputDecoration(
                          labelText: "Rating",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      attribute: "movie_rating",
                      borderColor: Colors.blue[800],
                      options: List.generate(5, (i) => i + 1)
                          .map(
                              (number) => FormBuilderFieldOption(value: number))
                          .toList(),
                    ),
                    SizedBox(height: 10),
                    FormBuilderStepper(
                      decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.black26),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        contentPadding: EdgeInsets.all(4),
                          labelText: "Stepper",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      attribute: "stepper",
                      initialValue: 10,
                      step: 1,
                    ),
                    SizedBox(height: 10),
                    FormBuilderCheckboxList(
                      decoration:
                      InputDecoration(labelText: "Languages you know"),
                      attribute: "languages",
                      initialValue: ["English"],
                      activeColor: Colors.blue[800],
                      options: [
                        FormBuilderFieldOption(value: "English",),
                        FormBuilderFieldOption(value: "Hindi"),
                        FormBuilderFieldOption(value: "Other")
                      ],
                    ),
                    SizedBox(height: 10),
                    FormBuilderSignaturePad(
                      decoration: InputDecoration(
                          labelText: "Signature",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      attribute: "signature",
                      height: 100,
                    ),
                    FormBuilderRate(
                      decoration: InputDecoration(
                          labelText: "Rate this site",
                        labelStyle:   Theme.of(context).textTheme.body1,
                      ),
                      attribute: "rate",
                      filledColor: Colors.blue[800],
                      iconSize: 32.0,
                      initialValue: 1,
                      max: 5,
                    ),
                    SizedBox(height: 10),
                    FormBuilderCheckbox(
                      attribute: 'accept_terms',
                      label: Text(
                          "I have read and agree to the terms and conditions",style: TextStyle(
                        color: Colors.black54,fontWeight: FontWeight.bold
                      ),),
                      validators: [
                        FormBuilderValidators.requiredTrue(
                          errorText:
                          "You must accept terms and conditions to continue",
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 10),
              Row(
                children: <Widget>[
                  MaterialButton(
                    child: Text("Submit",style: TextStyle(color: Colors.white),),
                    color: Colors.green,
                    onPressed: () {
                      _fbKey.currentState.save();
                      if (_fbKey.currentState.validate()) {
                        print(_fbKey.currentState.value);
                      }
                    },
                  ),
                  SizedBox(width: 20),
                  MaterialButton(
                    child: Text("Reset",style: TextStyle(color: Colors.white),),
                    color: Colors.red,
                    onPressed: () {
                      _fbKey.currentState.reset();
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

Related Post