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?
Just select an element (maybe the button, panel or the window) and use the "Code"-tab in the "Properties"-dialog.
selection = TextSelection( baseOffset: 0, extentOffset: textValue. length, ); In the TextFormField, make sure to assign the controller and set autofocus to true. That's it!
To listen to focus change, you can add a listner to the FocusNode and specify the focusNode to TextField . This gist represents how to ensure a focused node to be visible on the ui. Hope it helps!
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,
);
});
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),
)
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!
As of Dart 2:
controller1.selection = TextSelection(baseOffset:0, extentOffset:controller1.text.length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With