Flutter – Build a Form
Last Updated :
16 Oct, 2023
The Form widget in Flutter is a fundamental widget for building forms. It provides a way to group multiple form fields together, 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 about what we are going to do in this article.
Some Properties of Form Widget
- 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, ListView, 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
- 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,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: <Widget>[
],
),
)
|
Required Tools
To build this app, you need the following items installed on your machine:
- Visual Studio Code / Android Studio
- Android Emulator / iOS Simulator / Physical Device device.
- Flutter Installed
- Flutter plugin for VS Code / Android Studio.
Step By Step Implementations
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to 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: Execute the main Method
Here the execution of our app starts.
Dart
void main() => runApp(MyApp());
|
Step 4: Create MyApp Class
In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.
Dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData(
primarySwatch: Colors.green,
),
title: 'Flutter Form Example' ,
home: MyForm(),
);
}
}
|
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.
Form(
key: _formKey, // Associate the form key with this Form widget
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'), // Label for the name field
validator: (value) {
// Validation function for the name field
if (value!.isEmpty) {
return 'Please enter your name.'; // Return an error message if the name is empty
}
return null; // Return null if the name is valid
},
onSaved: (value) {
_name = value!; // Save the entered name
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'), // Label for the email field
validator: (value) {
// Validation function for the email field
if (value!.isEmpty) {
return 'Please enter your email.'; // Return an error message if the email is empty
}
// You can add more complex validation logic here
return null; // Return null if the email is valid
},
onSaved: (value) {
_email = value!; // Save the entered email
},
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: _submitForm, // Call the _submitForm function when the button is pressed
child: Text('Submit'), // Text on the button
),
],
),
),
),
Dart
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _name = '' ;
String _email = '' ;
void _submitForm() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print( 'Name: $_name' );
print( 'Email: $_email' );
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text( 'Flutter Form Example' ),
),
body: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name' ),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your name.' ;
}
return null;
},
onSaved: (value) {
_name = value!;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email' ),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your email.' ;
}
return null;
},
onSaved: (value) {
_email = value!;
},
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: _submitForm,
child: Text( 'Submit' ),
),
],
),
),
),
);
}
}
|
Here is the full Code of main.dart file
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(
primarySwatch: Colors.green,
),
title: 'Flutter Form Example' ,
home: MyForm(),
);
}
}
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _name = '' ;
String _email = '' ;
void _submitForm() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print( 'Name: $_name' );
print( 'Email: $_email' );
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text( 'Flutter Form Example' ),
),
body: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name' ),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your name.' ;
}
return null;
},
onSaved: (value) {
_name = value!;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email' ),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your email.' ;
}
return null;
},
onSaved: (value) {
_email = value!;
},
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: _submitForm,
child: Text( 'Submit' ),
),
],
),
),
),
);
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...