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:
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. |
---|
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. |
---|
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 = '';
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'),
),
],
),
),
),
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:
Similar Reads
Flutter - Build Hotel Search App The world of mobile applications has seen a tremendous surge in the travel and tourism sector. In this tutorial, we will explore how to develop a hotel search app using Flutter, a powerful cross-platform framework. Flutter provides a rich set of tools and widgets for crafting engaging and performant
8 min read
Flutter - Dice Roller App Here, we will be building a simple dice app that rolls on click. For this, we will add a GestureDetector widget and when we click on it, the dice should roll. We can achieve this by wrapping the Image Widget in a GestureDetector Widget and changing dice images randomly in a callback function, which
4 min read
Flutter - Magic 8 Ball App We will be building a Magic 8-Ball app that will give you the answers to all fun, tricky questions (basically, it is a fun game app that will change its state of image using Textbutton in Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets and a Textbutton. Steps to build
3 min read
Flutter - Build a Inventory Management App Inventory management is a crucial aspect of any business. With the power of Flutter, we can create a simple yet effective inventory management app. In this tutorial, we'll build a basic inventory manager using Flutter and local storage. A sample video is given below to get an idea about what we are
6 min read
Flutter - Build Language Learning App In this article, we will explore how to create a language-learning app using Flutter, a popular open-source UI software development toolkit developed by Google. Flutter enables developers to build natively compiled applications for mobile, web, and desktop platforms from a single codebase. This make
13 min read
Flutter Bloc - Basic Search In this article, we are going to develop a Basic Search App using Flutter Bloc and Clean Architecture. In Flutter applications, the Flutter BLoC (Business Logic Component) is used to manage the state. It helps separate business logic from UI. It ensures that the user interface is not strongly liaiso
15+ min read
Flutter - Building a Tic Tac Toe Game Flutter SDK is an open-source software development kit for building beautiful UI that is natively compiled. In this article, we will build a Tic Tac Toe. Tic Tac Toe is a two-player game played on a 3x3 grid. One player uses "X" and the other "O." The goal is to be the first to get three of your sym
11 min read
Flutter - Build a Random Quote Generator App Flutter is a UI toolkit developed by Google back in 2007. It is the first choice of most beginner cross-platform developers because of its straightforward learning curve and simple syntax. Flutter provides a simple API to generate beautiful UI without a hassle. One can develop apps for many platform
3 min read
BLoC Pattern Flutter In Flutter applications, the Flutter BLoC (Business Logic Component) is used to manage the state. It helps separate business logic from UI. It ensures that the user interface is not strongly liaison with the business logic, making the app more versatile. It is powerful since it allows the creation o
10 min read
How to Disable a Button in Flutter? Sometimes we need to make the button disabled, let us consider, you created a form to take the user input and a form submit button. Then you want that, the button must be disabled until the user fills all the fields of the form then immediately enable the button. Sample Output is given below what we
3 min read