Automatically Selecting Text in a Flutter App

When using forms in a mobile app, often we are faced with the need to allow the user immediate access to a TextField and its contents so that the user has to only type the new input. The alternative is the user has to tap the TextField to establish focus, position the cursor or highlight a portion of the text, then delete the text or begin typing to insert or overwrite the selected text.

In my previous experience with React Native, this was fairly easy using the TextInput control. It provides a selectTextOnFocus prop to perform this action when the user focuses on the TextInput. A similar property isn’t available using the Flutter TextField widget. With the TextField widget, a few more steps are required but it provides more control over what gets selected during the process. The following steps show how this can be performed.

The TextField widget has a controller property. This property allows you to provide an initial text value to the widget and control selection of text. To use the controller for the selection it must first be instantiated.

String initialValue = 'Kevin A.";
TextEditingController controller = new TextEditingController(
	text: initialValue

Once instantiated, it provides the ability to select a portion or all of a text value using the selection property.

controller.selection = new TextSelection(
	baseOffset: 0, 
	extentOffset: initialValue.length,

As always, this is one of many possible ways to design this UI. If you feel this design could be improved, please feel free to leave me a comment.