Forms & Validation

June 02, 2026 1 min read

Flutter's Form + TextFormField handle input and validation cleanly.

final _formKey = GlobalKey<FormState>();
Form(
  key: _formKey,
  child: Column(children: [
    TextFormField(
      decoration: InputDecoration(labelText: 'Email'),
      validator: (v) => (v == null || !v.contains('@')) ? 'Invalid email' : null,
    ),
    ElevatedButton(
      onPressed: () {
        if (_formKey.currentState!.validate()) {
          // all fields valid — submit
        }
      },
      child: Text('Submit'),
    ),
  ]),
)
Tip: Return null from a validator when the value is valid, or an error string when it isn't.

Summary

Wrap fields in a Form with a GlobalKey, validate each TextFormField, and submit only when validate() passes.