Home > OS >  Flutter TextField cursor strange behaviour
Flutter TextField cursor strange behaviour

Time:06-01

I have the following problem with a TextField:
enter image description here

The cursor initially floats in the middle of the TextField above the text that has been set using a TextEditingController - when I try to enter something nothing happens. You have to click into the TextField and position the cursor at the end before you can enter something. This problem does somehow not occur when no TextEditingController is used.

TextField(
  autofocus: true,
  textAlign: TextAlign.center,
  controller: tec,
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
  ),
  keyboardType: TextInputType.number,
  onChanged: (value) {
    ...
  },
),

However I need a TextEditingController to initially set the text of the TextField. This is especially annoying as you often don't get why you can't enter something and don't realize that you have to place the cursor as the cursor is already within the TextField.

Is there any fix to this or e.g. a way to manually place the cursor at the end of the text?

[✓] Flutter (Channel stable, 3.0.1, on Arch Linux 5.17.7-arch1-1, locale
    de_DE.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 2021.2)
[✓] Connected device (3 available)
[✓] HTTP Host Availability

• No issues found!

CodePudding user response:

Use this snippet to place the cursor on the end:

controller.text = initialValue; //set your initial data
controller.selection = TextSelection.fromPosition(TextPosition(offset: controller.text.length));
  • Related