Home > Enterprise >  Get cursor position in a TextField
Get cursor position in a TextField

Time:08-15

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

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

One last thing, how do I handle if I double tap and select multiple characters?

CodePudding user response:

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);
  • Related