Open In App

Flutter – Build a Form

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

Some Methods of Form Widget

Basic Example of Form Widget




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

Required Tools

To build this app, you need the following items installed on your machine:



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.




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.




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      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
),
],
),
),
),




class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}
  
class _MyFormState extends State<MyForm> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); // A key for managing the form
  String _name = ''; // Variable to store the entered name
  String _email = ''; // Variable to store the entered email
  
  void _submitForm() {
    // Check if the form is valid
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save(); // Save the form data
      // 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(
        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
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Here is the full Code of main.dart file




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, // Set the app's primary theme color
      ),
      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>(); // A key for managing the form
  String _name = ''; // Variable to store the entered name
  String _email = ''; // Variable to store the entered email
  
  void _submitForm() {
    // Check if the form is valid
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save(); // Save the form data
      // 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(
        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
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Output:


Article Tags :