flutter-tutorial

Flutter Forms

Forms are an essential component of any current mobile and online apps. It is mostly used to interact with the app and to collect data from users. They can execute a variety of functions, according on your business requirements and logic, such as user authentication, user addition, searching, filtering, ordering, booking, and so on. Text fields, buttons, checkboxes, radio buttons, and other controls can be found on a form.

Creating Form

To create a form, Flutter provides a Form widget. The form widget serves as a container for several form fields, allowing us to group and validate them. It is required to give the GlobalKey while creating a form. This key identifies the form and allows you to perform any form field validation.

The TextFormField child widget is used by the form widget to allow users to enter text into the text field. This widget displays validation errors and renders a material design text field.

Let’s start by making a form. To begin, create a Flutter project and replace the code in the main.dart file with the following. We’ve developed a custom class called MyCustomForm in this code snippet. _formKey is a global key defined within this class. This key contains a FormState, which may be used to fetch the form widget. We’ve added some custom styling to this class’s create method, and we’re using the TextFormField widget to give form fields like name, phone number, date of birth, or simply a regular field. We used InputDecoration inside the TextFormField to offer the appearance and feel of your form features such as borders, labels, icons, hint, styles, and so on. Finally, we’ve put a submit button to the form.

Example:

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    final appTitle = 'Learn Code Zone';  
    return MaterialApp(  
      title: appTitle,  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text(appTitle),  
        ),  
        body: MyCustomForm(),  
      ),  
    );  
  }  
}  

class MyCustomForm extends StatefulWidget {  
  @override  
  MyCustomFormState createState() {  
    return MyCustomFormState();  
  }  
}  
 
class MyCustomFormState extends State<MyCustomForm> {  
  final _formKey = GlobalKey<FormState>();  
  
  @override  
  Widget build(BuildContext context) {  
    return Form(  
      key: _formKey,  
      child: Column(  
        crossAxisAlignment: CrossAxisAlignment.start,  
        children: <Widget>[  
          TextFormField(  
            decoration: const InputDecoration(  
              icon: const Icon(Icons.person),  
              hintText: 'Enter your name',  
              labelText: 'Name',  
            ),  
          ),  
          TextFormField(  
            decoration: const InputDecoration(  
              icon: const Icon(Icons.phone),  
              hintText: 'Enter a phone number',  
              labelText: 'Phone',  
            ),  
          ),  
          TextFormField(  
            decoration: const InputDecoration(  
            icon: const Icon(Icons.calendar_today),  
            hintText: 'Enter your date of birth',  
            labelText: 'Dob',  
            ),  
           ),  
          new Container(  
              padding: const EdgeInsets.only(left: 150.0, top: 40.0),  
              child: new RaisedButton(  
                child: const Text('Submit'),  
                  onPressed: null,  
              )),  
        ],  
      ),  
    );  
  }  
}  

Output

Now, run the app, you can see the following screen in your Android Emulator. This form contains three field name, phone number, date of birth, and submit button.

Form validation

Validation is a technique for correcting or confirming a set of standards. It guarantees that the data entered is authentic.

In all digital transactions, validating forms is a typical practise. In order to validate a form in flutter, we must follow three stages.

Step 1: Create a global key with the Form widget.

Step 2: Give the input field the validator property by using TextFormField.

Step 3: Create a button to validate form fields and display validation errors.

Let us comprehend it with the following example. To validate the input properties in the given code, we must utilise the validator() function in the TextFormField. The validator function delivers a string with an error message if the user provides incorrect input.

The validator() function can be written as below code snippets:

validator: (value) {  
       if (value.isEmpty) {  
             return 'Please enter some text';  
       }  
       return null;  
},  

Now, open the main.dart file and add validator() function in the TextFormField widget. Replace the following code with the main.dart file.

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    final appTitle = 'Flutter Form Demo';  
    return MaterialApp(  
      title: appTitle,  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text(appTitle),  
        ),  
        body: MyCustomForm(),  
      ),  
    );  
  }  
}  
// Create a Form widget.  
class MyCustomForm extends StatefulWidget {  
  @override  
  MyCustomFormState createState() {  
    return MyCustomFormState();  
  }  
}  
// Create a corresponding State class, which holds data related to the form.  
class MyCustomFormState extends State<MyCustomForm> {  
  // Create a global key that uniquely identifies the Form widget  
  // and allows validation of the form.  
  final _formKey = GlobalKey<FormState>();  
  
  @override  
  Widget build(BuildContext context) {  
    // Build a Form widget using the _formKey created above.  
    return Form(  
      key: _formKey,  
      child: Column(  
        crossAxisAlignment: CrossAxisAlignment.start,  
        children: <Widget>[  
          TextFormField(  
            decoration: const InputDecoration(  
              icon: const Icon(Icons.person),  
              hintText: 'Enter your full name',  
              labelText: 'Name',  
            ),  
            validator: (value) {  
              if (value.isEmpty) {  
                return 'Please enter some text';  
              }  
              return null;  
            },  
          ),  
          TextFormField(  
            decoration: const InputDecoration(  
              icon: const Icon(Icons.phone),  
              hintText: 'Enter a phone number',  
              labelText: 'Phone',  
            ),  
            validator: (value) {  
              if (value.isEmpty) {  
                return 'Please enter valid phone number';  
              }  
              return null;  
            },  
          ),  
          TextFormField(  
            decoration: const InputDecoration(  
            icon: const Icon(Icons.calendar_today),  
            hintText: 'Enter your date of birth',  
            labelText: 'Dob',  
            ),  
            validator: (value) {  
              if (value.isEmpty) {  
                return 'Please enter valid date';  
              }  
              return null;  
            },  
           ),  
          new Container(  
              padding: const EdgeInsets.only(left: 150.0, top: 40.0),  
              child: new RaisedButton(  
                child: const Text('Submit'),  
                onPressed: () {  
                  // It returns true if the form is valid, otherwise returns false  
                  if (_formKey.currentState.validate()) {  
                    // If the form is valid, display a Snackbar.  
                    Scaffold.of(context)  
                        .showSnackBar(SnackBar(content: Text('Data is in processing.')));  
                  }  
                },  
              )),  
        ],  
      ),  
    );  
  }  
}  

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.