onChange TextField move cursor to start in flutter
**If you want to move cursor dynamically with text **
setState(() {
String text = "sometext";
_controller.value = TextEditingValue(
text: text,
selection: TextSelection(
baseOffset: text.length,
extentOffset: text.length)
);
});
Set the selection using the TextEditingController
TextField(
controller: textEditController,
onChanged: (content) {
textEditController..text = checkNumber(content)
..selection = TextSelection.collapsed(offset: 0);
},
)
The accepted solution didn't work for me - as I was setting both text and selection I needed to instead set value.
The TextEditingController class documentation states:
The text or selection properties can be set from within a listener added to this controller. If both properties need to be changed then the controller's value should be set instead.
The documentation also has a relevant example that includes the following:
void initState() {
_controller.addListener(() {
final text = _controller.text.toLowerCase();
_controller.value = _controller.value.copyWith(
text: text,
selection: TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
});
super.initState();
}
This forces the entered text to be lower case and keeps the cursor at the end of the input.