xenos92
xenos92

Reputation: 351

Get cursor position in a TextField

I want to create a view with a TextField whose default behavior is disabled (i.e. I don't enable the default keyboard on click). I created my own keyboard because it allows me to do specific actions for my application. The keyboard works well and populates the TextField.


My problem

I can't manage the blinking cursor in the TextField. Indeed when I type on my keyboard the cursor follows my text so no problem. On the other hand, if I decide to click manually in the middle of my text, the cursor moves but the new characters entered do not go to the location of the cursor.

How to do this ?


What does it look like ?

enter image description here


My code

My TextField Widget:

InputAtom(
  autofocus: true,
  controller: controllerInput,
  placeholder: "Placeholder",
  fontSize: 35,
  keyboard: TextInputType.none,
  enableInteractiveSelection: true,
  showCursor: true,
  cursorColor: Colors.red,
  enableSuggestions: false,
  autocorrect: false,
),

My button keyboard example:

KeyboardButtonAtom.numeric({
    Key? key,
    required String text,
    required TextEditingController controller,
  }): super(
    key: key, 
    text: text,
    controller: controller,
    onPressed: (){
      // Here I add the number typed on the keyboard after
      controller.text += text.toString();
      // Here the cursor moves to the end of my controller.text
      controller.selection = TextSelection.collapsed(offset: controller.text.length);
      print(controller.selection.baseOffset);
    }
  );

How to retrieve the cursor position when I type somewhere by hand in my TextField to be able to add my numbers from the cursor position?



EDIT

In my KeyboardButtonAtom, I do that and it works. Thanks to @Kaushik Chandru Here is the code that works regardless of the position of the cursor even placed by hand in the middle of your character string

String textBeforeCursor = controller.text.substring(0, controller.selection.baseOffset);
String textAfterCursor =  controller.text.substring(controller.selection.extentOffset);
controller.text = textBeforeCursor + text.toString() + textAfterCursor;
int cursorPosition =  textBeforeCursor.length + 1;
controller.selection = TextSelection.collapsed(offset: cursorPosition);

Upvotes: 2

Views: 4369

Answers (1)

Kaushik Chandru
Kaushik Chandru

Reputation: 17822

To get the current position of the cursor you can try

var cursorPos = _textEditController.selection.base.offset;

String textAfterCursor =  _textEditController.text.substring(cursorPos);

String textBeforeCursor = _textEditController.text.substring(0, cursorPos);
 _textEditController.text = textBeforeCursor + "someText" + textAfterCursor;
                    
_textEditingController.selection = TextSelection.collapsed(offset: _textEditingController.text.length);

Upvotes: 8

Related Questions