Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 73 ยท Input and forms

Forms and Validation

Build Flutter forms with Form, TextFormField and a GlobalKey of FormState. Write validators, use controllers and focus nodes, and pick keyboard types.

Almost every app asks the user to type something: a login, a sign-up, an address, a search. Flutter gives you TextField for a single input, but once you have several fields that must be checked together, you want a form: a container that knows all its fields, can ask each one "are you valid?", and can show every error at once.

This lesson covers the Form widget, TextFormField, validators, controllers, focus and keyboard settings. It follows Gestures and input handling and uses StatefulWidget and setState for the screen's state.

Real vs stand-in. The Dart and widget code is real Flutter, shown read-only. The runnable examples are JavaScript stand-ins for the validation logic: a validator is just a function from text to "an error message or nothing", so it behaves the same way in any language.

Anatomy of a form

Form Groups the fields.
TextFormField One input with a validator.
GlobalKey Gives you the FormState.
validate() Runs every validator.
1 / 2

A first form

DART
class SignUpForm extends StatefulWidget {
  const SignUpForm({super.key});

  @override
  State<SignUpForm> createState() => _SignUpFormState();
}

class _SignUpFormState extends State<SignUpForm> {
  final _formKey = GlobalKey<FormState>();
  String _email = '';

  void _submit() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      debugPrint('Signing up $_email');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            decoration: const InputDecoration(labelText: 'Email'),
            keyboardType: TextInputType.emailAddress,
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'Please enter your email';
              }
              if (!value.contains('@')) {
                return 'That does not look like an email';
              }
              return null;
            },
            onSaved: (value) => _email = value!.trim(),
          ),
          const SizedBox(height: 16),
          FilledButton(onPressed: _submit, child: const Text('Sign up')),
        ],
      ),
    );
  }
}

The moving parts:

  • Form is an ordinary widget. It does not draw anything; it tracks the FormField widgets below it. TextFormField is a TextField wrapped in a FormField.
  • GlobalKey<FormState> is how your code reaches the form's State object from outside the tree. _formKey.currentState is null until the form is built, hence the ! (see Null safety). Keys are explained in Keys and widget identity.
  • validator receives the current text (a nullable String) and returns null for valid or an error string for invalid.
  • validate() calls every field's validator, rebuilds the fields that failed so they show their error under the input, and returns true only if all passed.
  • save() calls every onSaved. It is an optional way to copy values out of the fields.

Validators are just functions

Because a validator is String? Function(String?), you can write small reusable ones and combine them:

DART
typedef Validator = String? Function(String? value);

String? required(String? value) =>
    (value == null || value.trim().isEmpty) ? 'This field is required' : null;

Validator minLength(int n) => (value) =>
    (value != null && value.length < n) ? 'Use at least $n characters' : null;

Validator all(List<Validator> checks) => (value) {
      for (final check in checks) {
        final error = check(value);
        if (error != null) return error; // first error wins
      }
      return null;
    };

// Usage:
// validator: all([required, minLength(8)]),

Showing only the first error per field keeps the UI calm. Order the checks from most basic ("not empty") to most specific.

Stand-in: a validator pipeline

The next example builds the same required, minLength and all helpers and a mini form whose validate() visits every field, like the real FormState.

JS A validator pipeline and a mini FormState

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first run reports two errors at once, which is what a real Form does: it does not stop at the first failing field.

When to validate

TextFormField has an autovalidateMode:

  • AutovalidateMode.disabled (default): validate only when you call validate().
  • AutovalidateMode.always: show errors from the first frame, which annoys users who have not typed yet.
  • AutovalidateMode.onUserInteraction: validate a field after the user has touched it. This is usually the friendliest choice.

A common pattern is to leave it disabled until the first failed submit, then switch to onUserInteraction so errors disappear as soon as the user fixes them.

Controllers

onSaved is fine for simple forms. When you need to read, set or listen to the text at any time, use a TextEditingController:

DART
class _LoginState extends State<Login> {
  final _email = TextEditingController();
  final _password = TextEditingController();

  @override
  void dispose() {
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(controller: _email),
        TextFormField(controller: _password, obscureText: true),
        FilledButton(
          onPressed: () => debugPrint('${_email.text} / ${_password.text}'),
          child: const Text('Log in'),
        ),
      ],
    );
  }
}

A controller is a ChangeNotifier that holds the text and selection. Create it once in the State (never inside build), and always dispose it. You can set controller.text = 'hello' or controller.clear() to change the field from code, and controller.addListener(...) to react to every keystroke. The listener idea is the subject of Lifting state up and ValueNotifier.

Focus and the keyboard

Users expect Enter or "Next" to move to the following field. Flutter models keyboard focus with FocusNodes:

DART
final _emailFocus = FocusNode();
final _passwordFocus = FocusNode();

TextFormField(
  focusNode: _emailFocus,
  textInputAction: TextInputAction.next,
  onFieldSubmitted: (_) => _passwordFocus.requestFocus(),
),
TextFormField(
  focusNode: _passwordFocus,
  textInputAction: TextInputAction.done,
  onFieldSubmitted: (_) => _submit(),
),

Dispose focus nodes as well. To dismiss the keyboard, call FocusScope.of(context).unfocus().

The keyboardType picks the on-screen keyboard layout, and it does not validate anything:

Value Use for
TextInputType.emailAddress Email (shows @)
TextInputType.number Numbers
TextInputType.phone Phone numbers
TextInputType.multiline Long text (pair with maxLines)
TextInputType.url Web addresses

To limit what can be typed, add inputFormatters, such as FilteringTextInputFormatter.digitsOnly. Use autofillHints: [AutofillHints.email] so password managers can help.

Cross-field rules

A validator only sees its own field's value. For "confirm password" it needs to read the other field, so use a controller:

DART
TextFormField(
  controller: _confirm,
  obscureText: true,
  validator: (value) =>
      value == _password.text ? null : 'Passwords do not match',
),

Server-side errors

Client validation is a convenience, never security. The server must check everything again, and may reject data your validators accepted ("that email is already taken"). Keep an String? _serverError in State and return it from the validator, or show it with InputDecoration(errorText: ...), then call setState.

JS Cross-field and server-side errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Creating GlobalKey or controllers inside build. They are recreated every rebuild and the form loses its state. Create them in State.
  • Forgetting dispose for controllers and focus nodes.
  • Putting a form in a Column inside a Column without scrolling. When the keyboard opens the screen overflows; wrap the form in a SingleChildScrollView or ListView.
  • Treating keyboardType: number as validation. Users can still paste letters.
  • Using the same GlobalKey for two forms on screen at once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a TextFormField validator return when the input is valid?

    A validator returns null for valid input, or an error String to display.
  2. 2. How do you run every validator in a form from a button handler?

    The GlobalKey<FormState> gives access to FormState, whose validate() checks all fields and returns whether all passed.
  3. 3. Where should a TextEditingController be created and disposed?

    Controllers must outlive rebuilds, so the State owns them, and dispose releases their listeners.
  4. 4. What does keyboardType: TextInputType.number do?

    It only picks the keyboard. Use validators and inputFormatters to enforce the content.

Summary

  • Form plus TextFormField plus a GlobalKey<FormState> lets you validate all fields with one validate() call.
  • A validator is a function returning null (valid) or an error string; combine small validators into a pipeline.
  • Use autovalidateMode: onUserInteraction for friendly feedback.
  • Own controllers and focus nodes in State and dispose them; use textInputAction and requestFocus to move between fields.
  • Client checks are a convenience; the server must validate again and can report its own errors.

Next: Lifting State Up and ValueNotifier