secret
secret

Reputation: 825

Flutter Cursor Position on Text Field

I want to append text after the cursor position. For example: when the user moved the cursor of the text field middle. I want to get the cursor location on the text and I'll add text after the cursor location.

I tried with Text Edit Controller but I can't reach the cursor location with this. How can detect the cursor location on the text field?

Upvotes: 13

Views: 11611

Answers (3)

Alex.F
Alex.F

Reputation: 6181

An alternative to @secret's answer

final selection = textController.selection;
final offset = selection.baseOffset;
textController.value = textController.value.replaced(TextRange.collapsed(offset), someText);

Upvotes: 3

Jabaseelan S
Jabaseelan S

Reputation: 49

int position =  controller.selection.base.offset;

simply get the cursor position and split it by firstpart and secondpart add the text what you want to insert. like

controller.text=firstpart+"someText"+lastpart;

Upvotes: 2

secret
secret

Reputation: 825

I fixed my problem with this;

// Get cursor current position
                    var cursorPos =
                        _textEditController.selection.base.offset;

                    // Right text of cursor position
                    String suffixText =
                        _textEditController.text.substring(cursorPos);

                    // Add new text on cursor position
                    String specialChars = ' text_1 ';
                    int length = specialChars.length;
                    
                    // Get the left text of cursor
                    String prefixText =
                        _textEditController.text.substring(0, cursorPos);

                    _textEditController.text =
                        prefixText + specialChars + suffixText;
                    
                    // Cursor move to end of added text
                    _textEditController.selection = TextSelection(
                      baseOffset: cursorPos + length,
                      extentOffset: cursorPos + length,
                    );

Upvotes: 16

Related Questions