Reputation: 825
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
Reputation: 6181
final selection = textController.selection;
final offset = selection.baseOffset;
textController.value = textController.value.replaced(TextRange.collapsed(offset), someText);
Upvotes: 3
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
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