TextFormField class

A FormField that contains a TextField.

This is a convenience widget that wraps a TextField widget in a FormField.

A Form ancestor is not required. The Form allows one to save, reset, or validate multiple fields at once. To use without a Form, pass a GlobalKey<FormFieldState> (see GlobalKey) to the constructor and use GlobalKey.currentState to save or reset the form field.

When a controller is specified, its TextEditingController.text defines the initialValue. If this FormField is part of a scrolling container that lazily constructs its children, like a ListView or a CustomScrollView, then a controller should be specified. The controller's lifetime should be managed by a stateful widget ancestor of the scrolling container.

If a controller is not specified, initialValue can be used to give the automatically generated controller an initial value.

When the widget has focus, it will prevent itself from disposing via its underlying EditableText's AutomaticKeepAliveClientMixin.wantKeepAlive in order to avoid losing the selection. Removing the focus will allow it to be disposed.

Remember to call TextEditingController.dispose of the TextEditingController when it is no longer needed. This will ensure any resources used by the object are discarded.

By default, decoration will apply the ambient InputDecorationThemeData for the current context to the InputDecoration, see InputDecoration.applyDefaults.

For a documentation about the various parameters, see TextField.

Creates a TextFormField with an InputDecoration and validator function.

If the user enters valid text, the TextField appears normally without any warnings to the user

If the user enters invalid text, the error message returned from the validator function is displayed in dark red underneath the input

TextFormField(
  decoration: const InputDecoration(
    icon: Icon(Icons.person),
    hintText: 'What do people call you?',
    labelText: 'Name *',
  ),
  onSaved: (String? value) {
    // This optional block of code can be used to run
    // code when the user saves the form.
  },
  validator: (String? value) {
    return (value != null && value.contains('@')) ? 'Do not use the @ char.' : null;
  },
)

This example shows how to move the focus to the next field when the user presses the SPACE key.

To see it in action, copy and run this code snippet on DartPad.

import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';

/// Flutter code sample for [TextFormField].

void main() => runApp(const TextFormFieldExampleApp());

class TextFormFieldExampleApp extends StatelessWidget {
  const TextFormFieldExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: TextFormFieldExample());
  }
}

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

  @override
  State<TextFormFieldExample> createState() => _TextFormFieldExampleState();
}

class _TextFormFieldExampleState extends State<TextFormFieldExample> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Shortcuts(
          shortcuts: const <ShortcutActivator, Intent>{
            // Pressing space in the field will now move to the next field.
            SingleActivator(LogicalKeyboardKey.space): NextFocusIntent(),
          },
          child: FocusTraversalGroup(
            child: Form(
              autovalidateMode: .always,
              onChanged: () {
                Form.of(primaryFocus!.context!).save();
              },
              child: Wrap(
                children: List<Widget>.generate(5, (int index) {
                  return Padding(
                    padding: const .all(8.0),
                    child: ConstrainedBox(
                      constraints: BoxConstraints.tight(const Size(200, 50)),
                      child: TextFormField(
                        onSaved: (String? value) {
                          debugPrint(
                            'Value for field $index saved as "$value"',
                          );
                        },
                      ),
                    ),
                  );
                }),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

This example shows how to force an error text to the field after making an asynchronous call.

To see it in action, copy and run this code snippet on DartPad.

import 'package:material_ui/material_ui.dart';

/// Flutter code sample for [TextFormField].

const Duration kFakeHttpRequestDuration = Duration(seconds: 3);

void main() => runApp(const TextFormFieldExampleApp());

class TextFormFieldExampleApp extends StatelessWidget {
  const TextFormFieldExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: TextFormFieldExample());
  }
}

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

  @override
  State<TextFormFieldExample> createState() => _TextFormFieldExampleState();
}

class _TextFormFieldExampleState extends State<TextFormFieldExample> {
  final TextEditingController controller = TextEditingController();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String? forceErrorText;
  bool isLoading = false;

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  String? validator(String? value) {
    if (value == null || value.isEmpty) {
      return 'This field is required';
    }
    if (value.length != value.replaceAll(' ', '').length) {
      return 'Username must not contain any spaces';
    }
    if (int.tryParse(value[0]) != null) {
      return 'Username must not start with a number';
    }
    if (value.length <= 2) {
      return 'Username should be at least 3 characters long';
    }
    return null;
  }

  void onChanged(String value) {
    // Nullify forceErrorText if the input changed.
    if (forceErrorText != null) {
      setState(() {
        forceErrorText = null;
      });
    }
  }

  Future<void> onSave() async {
    // Providing a default value in case this was called on the
    // first frame, the [fromKey.currentState] will be null.
    final bool isValid = formKey.currentState?.validate() ?? false;
    if (!isValid) {
      return;
    }

    setState(() => isLoading = true);
    final String? errorText = await validateUsernameFromServer(controller.text);

    if (context.mounted) {
      setState(() => isLoading = false);

      if (errorText != null) {
        setState(() {
          forceErrorText = errorText;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Padding(
        padding: const .symmetric(horizontal: 24.0),
        child: Center(
          child: Form(
            key: formKey,
            child: Column(
              mainAxisAlignment: .center,
              children: <Widget>[
                TextFormField(
                  forceErrorText: forceErrorText,
                  controller: controller,
                  decoration: const InputDecoration(
                    hintText: 'Please write a username',
                  ),
                  validator: validator,
                  onChanged: onChanged,
                ),
                const SizedBox(height: 40.0),
                if (isLoading)
                  const CircularProgressIndicator()
                else
                  TextButton(onPressed: onSave, child: const Text('Save')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Future<String?> validateUsernameFromServer(String username) async {
  final Set<String> takenUsernames = <String>{'jack', 'alex'};

  await Future<void>.delayed(kFakeHttpRequestDuration);

  final bool isValid = !takenUsernames.contains(username);
  if (isValid) {
    return null;
  }

  return 'Username $username is already taken';
}

See also:

Inheritance

Constructors

TextFormField({Key? key, Object groupId = EditableText, TextEditingController? controller, String? initialValue, FocusNode? focusNode, String? forceErrorText, InputDecoration? decoration = const InputDecoration(), TextInputType? keyboardType, TextCapitalization textCapitalization = TextCapitalization.none, TextInputAction? textInputAction, TextStyle? style, StrutStyle? strutStyle, TextDirection? textDirection, TextAlign textAlign = TextAlign.start, TextAlignVertical? textAlignVertical, bool autofocus = false, bool readOnly = false, @Deprecated('Use `contextMenuBuilder` instead. ' 'This feature was deprecated after v3.3.0-0.5.pre.') ToolbarOptions? toolbarOptions, bool? showCursor, String obscuringCharacter = '•', bool obscureText = false, bool autocorrect = true, SmartDashesType? smartDashesType, SmartQuotesType? smartQuotesType, bool enableSuggestions = true, MaxLengthEnforcement? maxLengthEnforcement, int? maxLines = 1, int? minLines, bool expands = false, int? maxLength, ValueChanged<String>? onChanged, GestureTapCallback? onTap, bool onTapAlwaysCalled = false, TapRegionCallback? onTapOutside, TapRegionUpCallback? onTapUpOutside, VoidCallback? onEditingComplete, ValueChanged<String>? onFieldSubmitted, FormFieldSetter<String>? onSaved, FormFieldValidator<String>? validator, FormFieldErrorBuilder? errorBuilder, List<TextInputFormatter>? inputFormatters, bool? enabled, bool? ignorePointers, double cursorWidth = 2.0, double? cursorHeight, Radius? cursorRadius, Color? cursorColor, Color? cursorErrorColor, Brightness? keyboardAppearance, EdgeInsets scrollPadding = const EdgeInsets.all(20.0), bool? enableInteractiveSelection, bool? selectAllOnFocus, TextSelectionControls? selectionControls, InputCounterWidgetBuilder? buildCounter, ScrollPhysics? scrollPhysics, Iterable<String>? autofillHints, AutovalidateMode? autovalidateMode, ScrollController? scrollController, String? restorationId, bool enableIMEPersonalizedLearning = true, MouseCursor? mouseCursor, EditableTextContextMenuBuilder? contextMenuBuilder = _defaultContextMenuBuilder, SpellCheckConfiguration? spellCheckConfiguration, TextMagnifierConfiguration? magnifierConfiguration, UndoHistoryController? undoController, AppPrivateCommandCallback? onAppPrivateCommand, bool? cursorOpacityAnimates, BoxHeightStyle? selectionHeightStyle, BoxWidthStyle? selectionWidthStyle, DragStartBehavior dragStartBehavior = DragStartBehavior.start, ContentInsertionConfiguration? contentInsertionConfiguration, MaterialStatesController? statesController, Clip clipBehavior = Clip.hardEdge, @Deprecated('Use `stylusHandwritingEnabled` instead. ' 'This feature was deprecated after v3.27.0-0.2.pre.') bool scribbleEnabled = true, bool stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, bool canRequestFocus = true, List<Locale>? hintLocales})
Creates a FormField that contains a TextField.

Properties

autovalidateMode AutovalidateMode
Used to enable/disable this form field auto validation and update its error text.
finalinherited
builder FormFieldBuilder<String>
Function that returns the widget representing this form field.
finalinherited
controller TextEditingController?
Controls the text being edited.
final
enabled bool
Whether the form is able to receive user input.
finalinherited
errorBuilder FormFieldErrorBuilder?
Function that returns the widget representing the error to display.
finalinherited
forceErrorText String?
An optional property that forces the FormFieldState into an error state by directly setting the FormFieldState.errorText property without running the validator function.
finalinherited
groupId Object
The group identifier for the TextFieldTapRegion of this text field.
final
hashCode int
The hash code for this object.
no setterinherited
initialValue String?
An optional value to initialize the form field to, or null otherwise.
finalinherited
key Key?
Controls how one widget replaces another widget in the tree.
finalinherited
onChanged ValueChanged<String>?
Called when the user initiates a change to the TextField's value: when they have inserted or deleted text or reset the form.
final
onReset VoidCallback?
An optional method to call when the form field is reset via FormFieldState.reset.
finalinherited
onSaved FormFieldSetter<String>?
An optional method to call with the final value when the form is saved via FormState.save.
finalinherited
restorationId String?
Restoration ID to save and restore the state of the form field.
finalinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
validator FormFieldValidator<String>?
An optional method that validates an input. Returns an error string to display if the input is invalid, or null otherwise.
finalinherited

Methods

createElement() StatefulElement
Creates a StatefulElement to manage this widget's location in the tree.
inherited
createState() FormFieldState<String>
Creates the mutable state for this widget at a given location in the tree.
override
debugDescribeChildren() List<DiagnosticsNode>
Returns a list of DiagnosticsNode objects describing this node's children.
inherited
debugFillProperties(DiagnosticPropertiesBuilder properties) → void
Add additional properties associated with the node.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) DiagnosticsNode
Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.
inherited
toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) String
A string representation of this object.
inherited
toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) String
Returns a string representation of this node and its descendants.
inherited
toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) String
Returns a one-line detailed description of the object.
inherited
toStringShort() String
A short, textual description of this widget.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited