Flutter TextField cursor position

Ngchiwa Ng
1 min readJul 20, 2021

--

sometimes, we need use text field and init text value in text field

you might

//in build methodreturn TextField(   controller: TextEditingController()..text = viewModel.text
onChange: (text) {
viewModel.text = text
})

what happen in this code?

  • when the rebuild will new TextEditingController , and the cursor will ship to wrong position :(

event you change TextEditingController scope the class scope

TextEditingController textEditingController = TextEditingController()//in build method
this.textEditingController..text = viewModel.text
return TextField( controller: textEditingController
onChange: (text) {
viewModel.text = text
});

solution:

only set the text in when you need to change Text value (not user affect the text value, ex: user tap the keyboard)

for example:

@overridevoid initState() {
super.initState();
this.textEditingController.text = "some text"
}
//in build method, just set the controller
return TextField(
controller: textEditingController
onChange: (text) {
viewModel.text = text
});

or you need change value after do something , (ex: call api)

@overridevoid callApi() {
// call api and set value
this.textEditingController.text = "api response";
}
//in build method, just set the controller
return TextField(
controller: textEditingController
onChange: (text) {
viewModel.text = text
});

hope this tips can help you if you struggle with Flutter TextField

#flutter

--

--

Ngchiwa Ng
Ngchiwa Ng

Written by Ngchiwa Ng

Backend/iOS Engineer, rock the world

No responses yet