How to implement Form widget and validation in Flutter

In this article, we will discuss the use of the Form widget in flutter and also add validation to it. What shall we do today is to add two text fields i.e. one for email and another for password? First of all, we should know some basic information about the form widget.

Forms are one of the integral parts of all modern mobile and web applications. Its main function is to interact with the app as well as gather information from the users. So that they can perform many tasks, which depend on the nature of our business requirements and logic, such as authentication of the user, adding user, searching, filtering, ordering, booking, etc. A form can contain text fields, buttons, checkboxes, radio buttons, etc.

Generally, Flutter provides a Form widget to create a form. The form widget basically acts as one of the containers, which allows us to group and validate the multiple form fields. When we create a form, it is necessary to provide the GlobalKey. This key generally identifies the form and allows us to do any validation that is present in the form fields.

The form widget uses child widget TextFormField to provide the users to enter the text field. This widget renders a material design text field and also allows us to display validation errors when they occur.

How to create a form Widget in Flutter

Let’s take an example of how we can create a form in our application.

import 'package:flutter/material.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final formkey = GlobalKey<FormState>();
  TextEditingController emailcontroller = TextEditingController();
  TextEditingController passwordcontroller = TextEditingController();

  bool togglevisibilty = false;
  @override
  void dispose() {
    emailcontroller.dispose();
    passwordcontroller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('Login Page'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Form(
          key: formkey,
          child: Column(children: [
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextFormField(
                keyboardType: TextInputType.emailAddress,
                enabled: true,
                validator: (value) {
                  final regex = RegExp(
                      r'^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');

                  if (value == null || value == '') {
                    return 'Email is required';
                  } else if (!regex.hasMatch(value.trim())) {
                    return 'Email is not valid';
                  }
                  return null;
                },
                controller: emailcontroller,
                decoration: InputDecoration(
                    focusColor: Colors.green,
                    filled: true,
                    fillColor: Colors.white,
                    focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15),
                        borderSide: const BorderSide(color: Colors.green)),
                    enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15),
                        borderSide: const BorderSide(color: Colors.green)),
                    hintText: " Enter the Email",
                    prefixIcon: const Icon(Icons.email),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15))),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextFormField(
                obscureText: togglevisibilty,
                keyboardType: TextInputType.visiblePassword,
                validator: (password) {
                  if (password == null || password == '') {
                    return 'password is required';
                  } else if (password.length < 5) {
                    return 'Enter the min 5 password';
                  } else {
                    return null;
                  }
                },
                controller: passwordcontroller,
                decoration: InputDecoration(
                  focusColor: Colors.green,
                  labelText: "Enter the Password",
                  hintText: " Enter the password",
                  prefixIcon: const Icon(Icons.lock),
                  suffixIcon: IconButton(
                    onPressed: () {
                      setState(() {
                        togglevisibilty = !togglevisibilty;
                      });
                    },
                    icon: togglevisibilty
                        ? const Icon(Icons.visibility_off)
                        : const Icon(Icons.visibility),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            buildbutton(),
          ]),
        ),
      ),
    );
  }

  buildbutton() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25),
      ),
      child: ElevatedButton(
        onPressed: () {
          if (formkey.currentState!.validate()) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Login Successful'),
              ),
            );
          }
        },
        child: const Text('Login'),
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thank you for reading the guide on Creating Form with validation in Flutter. Also Read: Firebase Integration In Flutter Applications