Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onChange TextField move cursor to start in flutter

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)
like image 791
Saman Avatar asked Feb 21 '19 11:02

Saman


People also ask

How do I change cursor position?

Use the SetCursorPosition method to specify where the next write operation in the console window is to begin. If the specified cursor position is outside the area that is currently visible in the console window, the window origin changes automatically to make the cursor visible.

How do you change the cursor position at the end of the value in Flutter?

Answers 13 : of how to set cursor position at the end of the value in flutter in textfield. You need a FocusNode and set TextSelection to place the cursor.

What is TextEditingController Flutter?

TextEditingController class Null safety. A controller for an editable text field. Whenever the user modifies a text field with an associated TextEditingController, the text field updates value and the controller notifies its listeners.


2 Answers

Set the selection using the TextEditingController

TextField(
controller: textEditController,
onChanged: (content) {
  textEditController..text = checkNumber(content)
                    ..selection = TextSelection.collapsed(offset: 0);
  },
)
like image 81
Günter Zöchbauer Avatar answered Oct 08 '22 18:10

Günter Zöchbauer


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.

like image 27
Nick Avatar answered Oct 08 '22 18:10

Nick