0
0
FlutterHow-ToBeginner · 3 min read

How to Use FormKey in Flutter for Form Validation

In Flutter, use a GlobalKey as a formKey to identify and manage a Form widget. This key lets you validate and save the form fields by calling formKey.currentState!.validate() and formKey.currentState!.save().
📐

Syntax

To use a FormKey in Flutter, you first create a GlobalKey<FormState>. Then assign it to the key property of a Form widget. You can call methods like validate() and save() on formKey.currentState to control the form.

  • GlobalKey<FormState> formKey = GlobalKey<FormState>(); - creates the key.
  • Form(key: formKey, child: ...) - assigns the key to the form.
  • formKey.currentState!.validate() - checks if all fields are valid.
  • formKey.currentState!.save() - saves the form data.
dart
final GlobalKey<FormState> formKey = GlobalKey<FormState>();

Form(
  key: formKey,
  child: Column(
    children: [
      TextFormField(
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter some text';
          }
          return null;
        },
      ),
    ],
  ),
);
💻

Example

This example shows a simple form with a text field and a button. When the button is pressed, it uses the formKey to validate the input. If valid, it shows a success message.

dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FormKey Example')),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Form(
            key: formKey,
            child: Column(
              children: [
                TextFormField(
                  decoration: InputDecoration(labelText: 'Enter your name'),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Name cannot be empty';
                    }
                    return null;
                  },
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Form is valid!')),
                      );
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
Output
A screen with a text input labeled 'Enter your name' and a 'Submit' button. If the input is empty and you press Submit, an error message appears below the field. If filled, a message 'Form is valid!' appears at the bottom.
⚠️

Common Pitfalls

  • Not assigning the formKey to the Form widget's key property, so validation won't work.
  • Calling formKey.currentState without checking if it's null, which can cause errors.
  • Forgetting to call validate() before saving or submitting the form.
  • Using multiple forms without separate keys, causing state conflicts.
dart
/* Wrong: Missing key on Form */
Form(
  child: TextFormField(
    validator: (value) => value!.isEmpty ? 'Empty' : null,
  ),
);

/* Right: Assign key to Form */
final formKey = GlobalKey<FormState>();

Form(
  key: formKey,
  child: TextFormField(
    validator: (value) => value!.isEmpty ? 'Empty' : null,
  ),
);
📊

Quick Reference

Property/MethodPurpose
GlobalKey<FormState>Unique key to access form state
Form(key: formKey)Assigns key to form widget
formKey.currentState!.validate()Checks if all fields are valid
formKey.currentState!.save()Saves form data
TextFormField.validatorFunction to validate input
Property/MethodPurpose
GlobalKeyUnique key to access form state
Form(key: formKey)Assigns key to form widget
formKey.currentState!.validate()Checks if all fields are valid
formKey.currentState!.save()Saves form data
TextFormField.validatorFunction to validate input

Key Takeaways

Use a GlobalKey to manage and validate forms in Flutter.
Assign the formKey to the Form widget's key property to link them.
Call formKey.currentState!.validate() to check if inputs are valid before saving or submitting.
Always check for null on formKey.currentState to avoid runtime errors.
Each form should have its own unique GlobalKey to prevent state conflicts.