Femin Dharamshi
Femin Dharamshi

Reputation: 177

Flutter TextField get Selected Text

In android we can get the starting and ending index of selected text in an EditText using this :

int a = inputET.getSelectionStart();
int b = inputET.getSelectionEnd();

What is the flutter alternative for this in a TextField ?

Upvotes: 7

Views: 4367

Answers (3)

thinhhja2001
thinhhja2001

Reputation: 11

The solution of Fayaz above is a good solution. However, it will only work when you highlight the text from left to right( the baseOffset will be less than the extentOffset). If you highlight it from right to left, the baseOffSet will now be greater than the extentOffset. This will now cause range-error since the start index in the subString method will be greater than the end index. I have adjust some line of Fayaz's code to solve this problem

int start = textEditingController.selection.baseOffset <
        textEditingController.selection.extentOffset
    ? textEditingController.selection.baseOffset
    : textEditingController.selection.extentOffset;
int end = textEditingController.selection.baseOffset >
        textEditingController.selection.extentOffset
    ? textEditingController.selection.baseOffset
    : textEditingController.selection.extentOffset;
String selectedText = textEditingController.text.substring(start, end);

Upvotes: 0

mckbrd
mckbrd

Reputation: 1085

It can be a bit more straightforward than Fayaz's answer: with a TextField(controller: _textEditingController) one can access the selected text like this:

_textEditingController.selection.textInside(_textEditingController.text)

Upvotes: 9

Fayaz
Fayaz

Reputation: 2114

Lets say we have this widget in widget tree

TextField(controller: _textEditingController),

on some button press, consider to print the selected text

printSelectedText(){
   print(_textEditingController.text.substring(_textEditingController.selection.baseOffset,_textEditingController.selection.extentOffset));
}

Upvotes: 2

Related Questions