Open In App

Flutter - Build a Form

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Form widget in Flutter is a fundamental widget for building forms. It provides a way to group multiple form fields, perform validation on those fields, and manage their state. In this article, we are going to implement the Form widget and explore some properties and Methods of it. A sample video is given below to get an idea of what we are going to do in this article.

Demo Video:

Some Properties of Form Widget

Property

Description

key

A GlobalKey that uniquely identifies the Form. You can use this key to interact with the form, such as validating, resetting, or saving its state

child

The child widget that contains the form fields. Typically, this is a Column, a list view, or another widget that allows you to arrange the form fields vertically

autovalidateMode

An enum that specifies when the form should automatically validate its fields.

Some Methods of Form Widget

Method

Description

validate()

This method is used to trigger the validation of all the form fields within the Form. It returns true if all fields are valid; otherwise, false. You can use it to check the overall validity of the form before submitting it.

save()

This method is used to save the current values of all form fields. It invokes the onSaved callback for each field. Typically, this method is called after validation succeeds.

reset()

Resets the form to its initial state, clearing any user-entered data.

currentState

A getter that returns the current FormState associated with the Form.


Basic Example of Form Widget

Dart
Form(
  key: _formKey, // GlobalKey<FormState>
  autovalidateMode: AutovalidateMode.onUserInteraction,
  child: Column(
    children: <Widget>[
      // Form fields go here
    ],
  ),
)


Step-by-Step Implementations

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Import the Package

First of all, import material.dart file.

import 'package:flutter/material.dart';

Step 3: Working with main.dart:

Add the boilerplate code below in main.dart to create a basic structure with an AppBar and body using a Scaffold.

Dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Form Example',
      home: MyForm(),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Form Example'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body:// Code Here
    );
  }
}


Step 4: Initialize variables

Initialize the required variables in the _MyFormState class.

Dart
// A key for managing the form
final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); 

// Variable to store the entered name
String _name = ''; 

// Variable to store the entered email
String _email = ''; 


Step 5: Create MyForm Class

In this step we are going to create a Simple Form with 2 TextFields and a Submit Button,By pressing the submit button the details are extracted from the TextField and user can perform varrious operations on the Data. Comments are added for better understanding.

Dart
Form(
// Associate the form key with this Form widget
key: _formKey, 
child: Padding(
  padding: EdgeInsets.all(16.0),
  child: Column(
    children: <Widget>[
      TextFormField(
        decoration: InputDecoration(
          
          // Label for the name field
          labelText: 'Name',
          
          // Border style for the text field
          border: OutlineInputBorder(), 
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.green,
              width: 2.0,
            ), // Border color when focused
          ),
        ),
        validator: (value) {
          
          // Validation function for the name field
          if (value!.isEmpty) {
              
            // Return an error message if the name is empty
            return 'Please enter your name.'; 
          }
          
          // Return null if the name is valid
          return null; 
        },
        onSaved: (value) {
            
          // Save the entered name
          _name = value!; 
        },
      ),
      SizedBox(height: 20.0),
      TextFormField(
        decoration: InputDecoration(
            
          // Label for the email field
          labelText: 'Email', 
          
          // Border style for the text field
          border:
              OutlineInputBorder(), 
              
          // Border color when focused
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.green,
              width: 2.0,
            ), 
          ),
        ),
        
        validator: (value) {
          
          // Validation function for the email field
          if (value!.isEmpty) {
              
            // Return an error message if the email is empty
            return 'Please enter your email.'; 
          }
          
          // You can add more complex validation logic here
          return null; // Return null if the email is valid
        },
        onSaved: (value) {
          
          // Save the entered email
          _email = value!; 
        },
      ),
      SizedBox(height: 20.0),
      ElevatedButton(
        style: ElevatedButton.styleFrom(
            
          // Button background color
          backgroundColor: Colors.green, 
          
          // Button text color
          foregroundColor: Colors.white, 
        ),
        
        // Call the _submitForm function when the button is pressed
        onPressed: _submitForm,
        
        // Text on the button
        child: Text('Submit'), 
      ),
    ],
  ),
),
),


Step 5: Create _submitForm() method

Create a function named _submitForm() to check the form is valid or not, if it's valid then show an AlertDialog with title as 'Form Submitted', subtitle as Name and Email entered by user and TextButton to close AlertDialog box.

Dart
void _submitForm() {

// Check if the form is valid
if (_formKey.currentState!.validate()) {
    
  // Save the form data
  _formKey.currentState!.save(); 
  
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
          
        // Title of the dialog
        title: Text('Form Submitted'), 
        
        content: Text(
          'Name: $_name\nEmail: $_email',
        ), 
        
        // Display the entered name and email
        actions: <Widget>[
          TextButton(
            child: Text(
              'OK',
              style: TextStyle(color: Colors.green),
            ), 
            
            // Button to close the dialog
            onPressed: () {
                
              // Close the dialog
              Navigator.of(context).pop(); 
            },
          ),
        ],
      );
    },
  );
}
}


Complete Source Code

main.dart:

Dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
          
        // Set the app's primary theme color
        primarySwatch: Colors.green, 
      ),
      title: 'Flutter Form Example',
      home: MyForm(),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
    
  // A key for managing the form
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); 
  
  // Variable to store the entered name
  String _name = ''; 
  
  // Variable to store the entered email
  String _email = ''; 

  void _submitForm() {
      
    // Check if the form is valid
    if (_formKey.currentState!.validate()) {
      
      // Save the form data
      _formKey.currentState!.save(); 
      
      // You can perform actions with the form
      // data here and extract the details
      print('Name: $_name'); // Print the name
      print('Email: $_email'); // Print the email
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Form Example'),
      ),
      body: Form(
          
        // Associate the form key with this Form widget
        key: _formKey, 
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              TextFormField(
                  
                // Label for the name field
                decoration: InputDecoration(labelText: 'Name'), 
                validator: (value) {
                    
                  // Validation function for the name field
                  if (value!.isEmpty) {
                      
                    // Return an error message if the name is empty
                    return 'Please enter your name.'; 
                  }
                  
                  // Return null if the name is valid
                  return null; 
                },
                onSaved: (value) {
                    
                  // Save the entered name
                  _name = value!; 
                },
              ),
              TextFormField(
                  
                // Label for the email field
                decoration: InputDecoration(labelText: 'Email'), 
                validator: (value) {
                    
                  // Validation function for the email field
                  if (value!.isEmpty) {
                      
                    // Return an error message if the email is empty
                    return 'Please enter your email.'; 
                  }
                  
                  // You can add more complex validation logic here
                  return null; // Return null if the email is valid
                },
                onSaved: (value) {
                    
                  // Save the entered email
                  _email = value!; 
                },
              ),
              SizedBox(height: 20.0),
              ElevatedButton(
                  
                // Call the _submitForm function when
                // the button is pressed
                onPressed: _submitForm,
                
                // Text on the button
                child: Text('Submit'), 
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Output:



Next Article

Similar Reads