Table of contents
1.
Introduction
2.
Flutter Form Submission Page
2.1.
Step 1: Create a Form with a GlobalKey.
2.2.
Step 2: Add a TextFormField with validation logic
2.3.
Step 3: Create a button to validate and submit the form
3.
Frequently Asked Questions
3.1.
What is Flutter used for?
3.2.
What is the use of GlobalKeys?
3.3.
What is a widget, and what are the types of widgets?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Flutter Form Submission Page

Author SHIVAM SINHA
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Form Submission Page is used to submit the user-input data from the form, and this can be done in a number of ways in a flutter. And submitting the user-input data using TextFields is one of the most used ways. TextFields requires a controller of every text field we create in Flutter, but the forms in Flutter don’t require any textController to store data. It just needs 1 GlobalKey, which is set to FormState. In the coming Sections, we will dive deep into the flutter form submission page.

Flutter Form Submission Page

We will understand the flutter form submission page by creating a simple form with one text field and a submit button. If we click on the submit button, the form data will be validated, and if the validation is successful, it will submit the data. If the validation is unsuccessful, it will give a simple error message to let us know about the error.

To create this, we are going to follow some simple steps:-

Step 1: Create a Form with a GlobalKey.

First, we are going to create a form. The form widget will act as a container for grouping and validating multiple form fields.

To uniquely identify the form, we should provide a GlobalKey while creating the form.


import 'package:flutter/material.dart';
 
// Defining a custom Form widget.
class CustomForm extends StatefulWidget {
  const CustomForm({super.key});
 
  
  CustomFormState createState() {
    return CustomFormState();
  }
}
 
// Defining a corresponding State class.
class CustomFormState extends State<CustomForm> {

  final _formKey = GlobalKey<FormState>();
 
 
  Widget build(BuildContext context) {
    // Building a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          // Add TextFormFields and ElevatedButton here.
        ],
      ),
    );
  }
}

 

Step 2: Add a TextFormField with validation logic

The next step is to add TextFormField. This widget renders a material design text field and can display validation errors when they occur.

Input is validated by providing a validator() function to the TextFormField. If the value entered by the user is not valid, then the validator function will return an error message. If there are no errors, then the validator will return a null.

In this example, we create a validator that ensures the TextFormField isn't empty. If it is empty, then it will return a custom error message.

TextFormField(
  // passing the user entered text to validator
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
),

Step 3: Create a button to validate and submit the form

Now that you have a form with a text field provide a button that the user can tap to submit the information.

When the user attempts to submit the form, check if the form is valid. If it is, display a success message. If it isn’t (the text field has no content), display the error message. 

ElevatedButton(
  onPressed: () {
  
    // Validate returns true if the form is valid, or false otherwise.
    if (_formKey.currentState!.validate()) {
    
      // If the form is valid, display a snackbar. In the real world,
      // you'd often call a server or save the information in a database.
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Processing Data')),
      );
    }
  },
  child: const Text('Submit'),
),

 

Output:

If we enter any data in the text field and try to submit it using the button, then it should process the entered text and submit it.

             

 

If we try to submit the form without entering any text, it will give us an error, showing the custom error message.

                      

 

If we try to submit the form without entering any text, it will give us an error, showing the custom error message.

Now let’s see how it is working. For validating the form, we are using the _formKey that is created in step 1. We can use the _formKey.currentState() method to access the FormState, which is automatically created by Flutter while building a form. The FormState class contains the validate() method, which will run for each text field present in the form. If everything is satisfied, the validator() method will return true; otherwise, it will display the error message and return false.

Frequently Asked Questions

What is Flutter used for?

Flutter is Google's free and open-source UI framework for creating native mobile applications. Released in 2017, Flutter allows developers to build mobile applications with a single codebase and programming language. This capability makes building both iOS and Android apps simpler and faster.

What is the use of GlobalKeys?

GlobalKeys have two uses: they allow widgets to change parents anywhere in your app without losing state, or they can be used to access information about another widget in a completely different part of the widget tree. An example of the first scenario might if you wanted to show the same widget on two different screens, but holding all the same state, you’d want to use a GlobalKey.

What is a widget, and what are the types of widgets?

Each element on the screen of the Flutter app is a widget. The view of the screen completely depends upon the choice and sequence of the widgets used to build the app. And the structure of the code of an app is a tree of widgets. There are broadly two types of widgets in the flutter: Stateless Widget and Stateful Widget.

Conclusion

In this article, we have discussed the Flutter Form Submission by creating a simple application and we added validation as well.

Enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more with our Coding Ninjas Studio  Guided Path. If you want to sharpen your coding skills to the test, check out the mock test series and enter the contests on Coding Ninjas Studio! If you are a beginner and want to know what questions big giants like Amazon, Microsoft, and Uber ask, check the problemsinterview experiences, and interview bundle for placement preparations.

You may consider our paid courses curated by experts to give your career an edge over others!

Do Upvote and Happy Learning!

Live masterclass