On TextField foucus I want to select all text so that when the user starts typing the existing text gets deleted.

This will be alternative of : android:selectAllOnFocus="true" in Android.

How to achive this?


Solution 1: Günter Zöchbauer

Pass a controller and focusNode explicitly, then you have full control:

final _controller = TextEditingController(); 
final _focusNode = FocusNode();

initState() {
  super.initState();
  _focusNode.addListener(() {
    if(_focusNode.hasFocus) {
      _controller.selection = TextSelection(baseOffset: 0, extentOffset: _controller.text.length);
    }
  });
}

build() => TextField(controller: _controller, focusNode: _focusNode);

Update from https://github.com/flutter/flutter/issues/28307#issuecomment-467952074 to prevent endless loop:

_controller.addListener(() {
  final newText = _controller.text.toLowerCase();
  _controller.value = _controller.value.copyWith(
    text: newText,
    selection: TextSelection(baseOffset: newText.length, extentOffset: newText.length),
    composing: TextRange.empty,
  );
});


Solution 2: TSR

As of Dart 2:

 controller1.selection = TextSelection(baseOffset:0, extentOffset:controller1.text.length);


Solution 3: d____

It's also possible to set the selection in onTap event. Like this:

TextField(
    controller: _controller,
    onTap: () => _controller.selection = TextSelection(baseOffset: 0, extentOffset: _controller.value.text.length),
)


Solution 4: Tovi Newman

It's actually much easier than the accepted answer.

First initialize a TextEditingController.

final _controller = TextEditingController();

Then, somewhere within your build method (probably within your edit text logic), set the text and the selection props like so.

_controller.text = textValue;
_controller.selection = TextSelection(
    baseOffset: 0,
    extentOffset: textValue.length,
);

In the TextFormField, make sure to assign the controller and set autofocus to true.

TextFormField(
    controller: _controller,
    autofocus: true,
    //...more properties

That's it!


Solution 5: Baker

For a cleaner, reusable experience an Extension class method (see note below) is handy.

extension TextEditingControllerExt on TextEditingController {
  void selectAll() {
    if (text.isEmpty) return;
    selection = TextSelection(baseOffset: 0, extentOffset: text.length);
  }
}

On the field:

TextField(
  controller: myController,
  onTap: myController.selectAll
)

Example

On Dartpad: https://dartpad.dev/?id=271737b109637f90a2fe5ea55ea2ac43

Note

In extension classes, this can be omitted.

text is assumed to be: this.text i.e. <this instance of controller>.text

Same with selection being actually this.selection.