Form in Flutter

Create Free Backend With Appwrite

Forms in Flutter

Form widget is used to group multiple form fields, such as textbox, checkboxes, and buttons, to create a easy data entry experience.

Why Forms are Useful?

Form are important for building interactive and user-friendly applications. They are useful for the following reasons:

  • Data Collection: It is used to collect the user input data such as name, email, phone number, etc.
  • Validation: It is used to validate the user input data such as email, phone number, etc.
  • Submission: It is used to submit the user input data to the server.

Example 1: Basic Form in Flutter

In this example below, you will learn to create a form with First Name and Last Name fields.

Form(
  child: Column(
    children: [
      // Form fields go here
      TextFormField(
        decoration: InputDecoration(
          labelText: 'First Name',
          hintText: 'Enter your first name',
        ),
      ),
      TextFormField(
        decoration: InputDecoration(
          labelText: 'Last Name',
          hintText: 'Enter your last name',
        ),
      ),
    ],
  ),
)
Run Online

Example 2: Form with Validation in Flutter

In this example below, you will learn to create a form with First Name and Last Name fields with validation. You will learn more about validation in the next section.

final _formKey = GlobalKey<FormState>();
Form(
  key: _formKey,
  child: Column(
    children: [
      // Form fields go here
      TextFormField(
        decoration: const InputDecoration(
          labelText: 'First Name',
          hintText: 'Enter your first name',
        ),
        validator: (value) {
          if (value == "") {
            return 'Please enter your first name';
          }
          return null;
        },
      ),
      TextFormField(
        decoration: const InputDecoration(
          labelText: 'Last Name',
          hintText: 'Enter your last name',
        ),
        validator: (value) {
          if (value == "") {
            return 'Please enter your last name';
          }
          return null;
        },
      ),
      const SizedBox(height: 10),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // Perform submission logic
          }
        },
        child: const Text('Submit'),
      ),
    ],
  ),
),
Run Online
Info

Note: GlobalKey is a unique identifier for widgets. It is used to access the state of a widget from outside the widget.