TextField class
A Material Design text field.
A text field lets the user enter text, either with hardware keyboard or withan onscreen keyboard.
The text field calls theonChanged callback whenever the user changes thetext in the field. If the user indicates that they are done typing in thefield (e.g., by pressing a button on the soft keyboard), the text fieldcalls theonSubmitted callback.
To control the text that is displayed in the text field, use thecontroller. For example, to set the initial value of the text field, useacontroller that already contains some text. Thecontroller can alsocontrol the selection and composing region (and to observe changes to thetext, selection, and composing region).
By default, a text field has adecoration that draws a divider below thetext field. You can use thedecoration property to control the decoration,for example by adding a label or an icon. If you set thedecorationproperty to null, the decoration will be removed entirely, including theextra padding introduced by the decoration to save space for the labels.
Ifdecoration is non-null (which is the default), the text field requiresone of its ancestors to be aMaterial widget.
To integrate theTextField into aForm with otherFormField widgets,consider usingTextFormField.
When the widget has focus, it will prevent itself from disposing via itsunderlyingEditableText'sAutomaticKeepAliveClientMixin.wantKeepAlive inorder to avoid losing the selection. Removing the focus will allow it to bedisposed.
Remember to callTextEditingController.dispose on theTextEditingControllerwhen it is no longer needed. This will ensure we discard any resources usedby the object.
If this field is part of a scrolling container that lazily constructs itschildren, like aListView or aCustomScrollView, then acontrollershould be specified. The controller's lifetime should be managed by astateful widget ancestor of the scrolling container.
Obscured Input
To create a local project with this code sample, run:
flutter create --sample=material.TextField.1 mysample
Reading values
A common way to read a value from a TextField is to use theonSubmittedcallback. This callback is applied to the text field's current value whenthe user finishes editing.
To create a local project with this code sample, run:
flutter create --sample=material.TextField.2 mysample
Lifecycle
Upon completion of editing, like pressing the "done" button on the keyboard,two actions take place:
1st: Editing is finalized. The default behavior of this step includesan invocation ofonChanged. That default behavior can be overridden. SeeonEditingComplete for details.
2nd:onSubmitted is invoked with the user's input value.
onSubmitted can be used to manually move focus to another input widgetwhen a user finishes with the currently focused input widget.
When the widget has focus, it will prevent itself from disposing viaAutomaticKeepAliveClientMixin.wantKeepAlive in order to avoid losing theselection. Removing the focus will allow it to be disposed.
For most applications theonSubmitted callback will be sufficient forreacting to user input.
TheonEditingComplete callback also runs when the user finishes editing.It's different fromonSubmitted because it has a default value whichupdates the text controller and yields the keyboard focus. Applications thatrequire different behavior can override the defaultonEditingCompletecallback.
Keep in mind you can also always read the current string from a TextField'sTextEditingController usingTextEditingController.text.
Handling emojis and other complex characters
It's important to always usecharacters when dealing with userinput text that may contain complex characters. This will ensure thatextended grapheme clusters and surrogate pairs are treated as singlecharacters, as they appear to the user.
For example, when finding the length of some user input, usestring.characters.length. Do NOT usestring.length or evenstring.runes.length. For the complex character "👨👩👦", thisappears to the user as a single character, andstring.characters.lengthintuitively returns 1. On the other hand,string.length returns 8, andstring.runes.length returns 5!
In the live Dartpad example above, try typing the emoji 👨👩👦into the field and submitting. Because the example code measures the lengthwithvalue.characters.length, the emoji is correctly counted as a singlecharacter.
Keep the caret visible when focused
When focused, this widget will make attempts to keep the text area and itscaret (even whenshowCursor isfalse) visible, on these occasions:
- When the user focuses this text field and it is notreadOnly.
- When the user changes the selection of the text field, or changes thetext when the text field is notreadOnly.
- When the virtual keyboard pops up.
Troubleshooting Common Accessibility Issues
Customizing User Input Accessibility Announcements
To customize user input accessibility announcements triggered by textchanges, useSemanticsService.announce to make the desiredaccessibility announcement.
On iOS, the on-screen keyboard may announce the most recent inputincorrectly when aTextInputFormatter inserts a thousands separator toa currency value text field. The following example demonstrates how tosuppress the default accessibility announcements by always announcingthe content of the text field as a US currency value (the\$ insertsa dollar sign, the$newText interpolates thenewText variable):
onChanged: (String newText) { if (newText.isNotEmpty) { SemanticsService.announce('\$$newText', Directionality.of(context)); }}To create a local project with this code sample, run:
flutter create --sample=material.TextField.3 mysample
Scrolling Considerations
If thisTextField is not a descendant ofScaffold and is being usedwithin aScrollable or nestedScrollables, consider placing aScrollNotificationObserver above the rootScrollable that contains thisTextField to ensure proper scroll coordination forTextField and itscomponents likeTextSelectionOverlay.
Shift+Enter keyboard shortcut for inserting a new linein aTextField.To create a local project with this code sample, run:
flutter create --sample=material.TextField.4 mysample
See also:
- TextFormField, which integrates with theForm widget.
- InputDecorator, which shows the labels and other visual elements thatsurround the actual text editing widget.
- EditableText, which is the raw text editing control at the heart of aTextField. TheEditableText widget is rarely used directly unlessyou are implementing an entirely different design language, such asCupertino.
- material.io/design/components/text-fields.html
- Cookbook:Create and style a text field
- Cookbook:Handle changes to a text field
- Cookbook:Retrieve the value of a text field
- Cookbook:Focus and text fields
- Inheritance
Constructors
- TextField({Key?key,ObjectgroupId =EditableText,TextEditingController?controller,FocusNode?focusNode,UndoHistoryController?undoController,InputDecoration?decoration =const InputDecoration(),TextInputType?keyboardType,TextInputAction?textInputAction,TextCapitalizationtextCapitalization =TextCapitalization.none,TextStyle?style,StrutStyle?strutStyle,TextAligntextAlign =TextAlign.start,TextAlignVertical?textAlignVertical,TextDirection?textDirection,boolreadOnly =false,@Deprecated('Use `contextMenuBuilder` instead. ' 'This feature was deprecated after v3.3.0-0.5.pre.')ToolbarOptions?toolbarOptions,bool?showCursor,boolautofocus =false,MaterialStatesController?statesController,StringobscuringCharacter ='•',boolobscureText =false,bool?autocorrect,SmartDashesType?smartDashesType,SmartQuotesType?smartQuotesType,boolenableSuggestions =true,int?maxLines =1,int?minLines,boolexpands =false,int?maxLength,MaxLengthEnforcement?maxLengthEnforcement,ValueChanged<
String> ?onChanged,VoidCallback?onEditingComplete,ValueChanged<String> ?onSubmitted,AppPrivateCommandCallback?onAppPrivateCommand,List<TextInputFormatter> ?inputFormatters,bool?enabled,bool?ignorePointers,doublecursorWidth =2.0,double?cursorHeight,Radius?cursorRadius,bool?cursorOpacityAnimates,Color?cursorColor,Color?cursorErrorColor,BoxHeightStyle?selectionHeightStyle,BoxWidthStyle?selectionWidthStyle,Brightness?keyboardAppearance,EdgeInsetsscrollPadding =const EdgeInsets.all(20.0),DragStartBehaviordragStartBehavior =DragStartBehavior.start,bool?enableInteractiveSelection,bool?selectAllOnFocus,TextSelectionControls?selectionControls,GestureTapCallback?onTap,boolonTapAlwaysCalled =false,TapRegionCallback?onTapOutside,TapRegionUpCallback?onTapUpOutside,MouseCursor?mouseCursor,InputCounterWidgetBuilder?buildCounter,ScrollController?scrollController,ScrollPhysics?scrollPhysics,Iterable<String> ?autofillHints =const <String>[],ContentInsertionConfiguration?contentInsertionConfiguration,ClipclipBehavior =Clip.hardEdge,String?restorationId,@Deprecated('Use `stylusHandwritingEnabled` instead. ' 'This feature was deprecated after v3.27.0-0.2.pre.')boolscribbleEnabled =true,boolstylusHandwritingEnabled =EditableText.defaultStylusHandwritingEnabled,boolenableIMEPersonalizedLearning =true,EditableTextContextMenuBuilder?contextMenuBuilder =_defaultContextMenuBuilder,boolcanRequestFocus =true,SpellCheckConfiguration?spellCheckConfiguration,TextMagnifierConfiguration?magnifierConfiguration,List<Locale> ?hintLocales}) - Creates a Material Design text field.const
Properties
- autocorrect→bool?
- Whether to enable autocorrection.final
- autofillHints→Iterable<
String> ? - A list of strings that helps the autofill service identify the type of thistext input.final
- autofocus→bool
- Whether this text field should focus itself if nothing else is alreadyfocused.final
- buildCounter→InputCounterWidgetBuilder?
- Callback that generates a customInputDecoration.counter widget.final
- canRequestFocus→bool
- Determine whether this text field can request the primary focus.final
- clipBehavior→Clip
- The content will be clipped (or not) according to this option.final
- contentInsertionConfiguration→ContentInsertionConfiguration?
- Configuration of handler for media content inserted via the system inputmethod.final
- contextMenuBuilder→EditableTextContextMenuBuilder?
- Builds the text selection toolbar when requested by the user.final
- controller→TextEditingController?
- Controls the text being edited.final
- cursorColor→Color?
- The color of the cursor.final
- cursorErrorColor→Color?
- The color of the cursor when theInputDecorator is showing an error.final
- cursorHeight→double?
- How tall the cursor will be.final
- cursorOpacityAnimates→bool?
- Whether the cursor will animate from fully transparent to fully opaqueduring each cursor blink.final
- cursorRadius→Radius?
- How rounded the corners of the cursor should be.final
- cursorWidth→double
- How thick the cursor will be.final
- decoration→InputDecoration?
- The decoration to show around the text field.final
- dragStartBehavior→DragStartBehavior
- Determines the way that drag start behavior is handled.final
- enabled→bool?
- If false the text field is "disabled": it ignores taps and itsdecoration is rendered in grey.final
- enableIMEPersonalizedLearning→bool
- Whether to enable that the IME update personalized data such as typinghistory and user dictionary data.final
- enableInteractiveSelection→bool
- Whether to enable user interface affordances for changing thetext selection.final
- enableSuggestions→bool
- Whether to show input suggestions as the user types.final
- expands→bool
- Whether this widget's height will be sized to fill its parent.final
- focusNode→FocusNode?
- Defines the keyboard focus for this widget.final
- groupId→Object
- The group identifier for theTextFieldTapRegion of this text field.final
- hashCode→int
- The hash code for this object.no setterinherited
- hintLocales→List<
Locale> ? - List of the languages that the user is expected to use.final
- ignorePointers→bool?
- Determines whether this widget ignores pointer events.final
- inputFormatters→List<
TextInputFormatter> ? - Optional input validation and formatting overrides.final
- key→Key?
- Controls how one widget replaces another widget in the tree.finalinherited
- keyboardAppearance→Brightness?
- The appearance of the keyboard.final
- keyboardType→TextInputType
- The type of keyboard to use for editing the text.final
- magnifierConfiguration→TextMagnifierConfiguration?
- The configuration for the magnifier of this text field.final
- maxLength→int?
- The maximum number of characters (Unicode grapheme clusters) to allow inthe text field.final
- maxLengthEnforcement→MaxLengthEnforcement?
- Determines how themaxLength limit should be enforced.final
- maxLines→int?
- The maximum number of lines to show at one time, wrapping if necessary.final
- minLines→int?
- The minimum number of lines to occupy when the content spans fewer lines.final
- mouseCursor→MouseCursor?
- The cursor for a mouse pointer when it enters or is hovering over thewidget.final
- obscureText→bool
- Whether to hide the text being edited (e.g., for passwords).final
- obscuringCharacter→String
- Character used for obscuring text ifobscureText is true.final
- onAppPrivateCommand→AppPrivateCommandCallback?
- This is used to receive a private command from the input method.final
- onChanged→ValueChanged<
String> ? - Called when the user initiates a change to the TextField'svalue: when they have inserted or deleted text.final
- onEditingComplete→VoidCallback?
- Called when the user submits editable content (e.g., user presses the "done"button on the keyboard).final
- onSubmitted→ValueChanged<
String> ? - Called when the user indicates that they are done editing the text in thefield.final
- onTap→GestureTapCallback?
- Called for the first tap in a series of taps.final
- onTapAlwaysCalled→bool
- WhetheronTap should be called for every tap.final
- onTapOutside→TapRegionCallback?
- Called for each tap down that occurs outside of theTextFieldTapRegiongroup when the text field is focused.final
- onTapUpOutside→TapRegionUpCallback?
- Called for each tap up that occurs outside of theTextFieldTapRegiongroup when the text field is focused.final
- readOnly→bool
- Whether the text can be changed.final
- restorationId→String?
- Restoration ID to save and restore the state of the text field.final
- runtimeType→Type
- A representation of the runtime type of the object.no setterinherited
- scribbleEnabled→bool
- Whether iOS 14 Scribble features are enabled for this widget.final
- scrollController→ScrollController?
- TheScrollController to use when vertically scrolling the input.final
- scrollPadding→EdgeInsets
- Configures the padding for the edges surrounding aScrollable when thetext field scrolls into view.final
- scrollPhysics→ScrollPhysics?
- TheScrollPhysics to use when vertically scrolling the input.final
- selectAllOnFocus→bool?
- Whether this field should select all text when gaining focus.final
- selectionControls→TextSelectionControls?
- Optional delegate for building the text selection handles.final
- selectionEnabled→bool
- Same asenableInteractiveSelection.no setter
- selectionHeightStyle→BoxHeightStyle?
- Controls how tall the selection highlight boxes are computed to be.final
- selectionWidthStyle→BoxWidthStyle?
- Controls how wide the selection highlight boxes are computed to be.final
- showCursor→bool?
- Whether to show cursor.final
- smartDashesType→SmartDashesType
- Whether to allow the platform to automatically format dashes.final
- smartQuotesType→SmartQuotesType
- Whether to allow the platform to automatically format quotes.final
- spellCheckConfiguration→SpellCheckConfiguration?
- Configuration that details how spell check should be performed.final
- statesController→MaterialStatesController?
- Represents the interactive "state" of this widget in terms of a set ofWidgetStates, includingWidgetState.disabled,WidgetState.hovered,WidgetState.error, andWidgetState.focused.final
- strutStyle→StrutStyle?
- The strut style used for the vertical layout.final
- style→TextStyle?
- The style to use for the text being edited.final
- stylusHandwritingEnabled→bool
- Whether this input supports stylus handwriting, where the user can writedirectly on top of a field.final
- textAlign→TextAlign
- How the text should be aligned horizontally.final
- textAlignVertical→TextAlignVertical?
- How the text should be aligned vertically.final
- textCapitalization→TextCapitalization
- Configures how the platform keyboard will select an uppercase orlowercase keyboard.final
- textDirection→TextDirection?
- The directionality of the text.final
- textInputAction→TextInputAction?
- The type of action button to use for the keyboard.final
- toolbarOptions→ToolbarOptions?
- Configuration of toolbar options.final
- undoController→UndoHistoryController?
- Controls the undo state.final
Methods
- createElement(
)→StatefulElement - Creates aStatefulElement to manage this widget's location in the tree.inherited
- createState(
)→State< TextField> - Creates the mutable state for this widget at a given location in the tree.override
- debugDescribeChildren(
)→List< DiagnosticsNode> - Returns a list ofDiagnosticsNode objects describing this node'schildren.inherited
- debugFillProperties(
DiagnosticPropertiesBuilderproperties)→ void - Add additional properties associated with the node.override
- noSuchMethod(
Invocationinvocation)→ 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 debuggingtools and byDiagnosticsNode.toStringDeep.inherited
- toString(
{DiagnosticLevelminLevel =DiagnosticLevel.info})→String - A string representation of this object.inherited
- toStringDeep(
{StringprefixLineOne ='',String?prefixOtherLines,DiagnosticLevelminLevel =DiagnosticLevel.debug,intwrapWidth =65})→String - Returns a string representation of this node and its descendants.inherited
- toStringShallow(
{Stringjoiner =', ',DiagnosticLevelminLevel =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 ==(
Objectother)→bool - The equality operator.inherited
Static Methods
- defaultSpellCheckSuggestionsToolbarBuilder(
BuildContextcontext,EditableTextStateeditableTextState)→Widget - Default builder forTextField's spell check suggestions toolbar.
- inferAndroidSpellCheckConfiguration(
SpellCheckConfiguration?configuration)→SpellCheckConfiguration - Returns a newSpellCheckConfiguration where the given configuration hashad any missing values replaced with their defaults for the Androidplatform.
Constants
- materialMisspelledTextStyle→ constTextStyle
- TheTextStyle used to indicate misspelled words in the Material style.
- noMaxLength→ constint
- IfmaxLength is set to this value, only the "current input length"part of the character counter is shown.