How to get the raw text from a Flutter TextBox
Asked Answered
E

1

4

In Flutter, after a Paragraph or TextPainter has laid out it's text, you can get the Rects for the lines (or runs within a line) by calling getBoxesForSelection. If you draw the actual boxes they look something like this:

enter image description here

How do I programmatically get the text within each TextBox?

Electrophone answered 9/7, 2019 at 0:30 Comment(0)
E
8

I wish there were a better way, but this is the only way I have found so far:

// The TextPaint has already been laid out

// select everything
TextSelection selection = TextSelection(baseOffset: 0, extentOffset: textSpan.text.length);

// get a list of TextBoxes (Rects)
List<TextBox> boxes = _textPainter.getBoxesForSelection(selection);

// Loop through each text box
List<String> lineTexts = [];
int start = 0;
int end;
int index = -1;
for (TextBox box in boxes) {
  index += 1;

  // Uncomment this if you want to only get the whole line of text
  // (sometimes a single line may have multiple TextBoxes)
  // if (box.left != 0.0)
  //  continue;

  if (index == 0)
    continue;
  // Go one logical pixel within the box and get the position
  // of the character in the string.
  end = _textPainter.getPositionForOffset(Offset(box.left + 1, box.top + 1)).offset;
  // add the substring to the list of lines
  final line = rawText.substring(start, end);
  lineTexts.add(line);
  start = end;
}
// get the last substring
final extra = rawText.substring(start);
lineTexts.add(extra);

Notes:

  • To be more rebust, this should check the TextPosition affinity.
  • This doesn't handle right-to-left text yet.

Update:

  • If you are getting the text of the whole line, you can use LineMetrics (from TextPainter.computeLineMetrics()) now instead of TextBox. The process would be similar.
Electrophone answered 9/7, 2019 at 0:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.