onChange TextField move cursor to start in flutter

Saman picture Saman · Feb 21, 2019 · Viewed 10.9k times · Source

I try to check input with onChange method in TextField but after replacing text with TextEditingController cursor move to start of TextField.

This problem occurs only on the Android platform.

Code

TextField(
controller: textEditController,
onChanged: (content) {
                    textEditController.text = checkNumber(content);
                  },)

flutter version

[✓] Flutter (Channel master, v1.2.2-pre.41, on Mac OS X 10.14.3 18D109, locale
    en-IR)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)

Answer

Günter Zöchbauer picture Günter Zöchbauer · Feb 21, 2019

Set the selection using the TextEditingController

TextField(
controller: textEditController,
onChanged: (content) {
  textEditController..text = checkNumber(content)
                    ..selection = TextSelection.collapsed(offset: 0);
  },
)