How to get the raw text from a Flutter TextBox

孤者浪人 提交于 2019-12-13 03:19:32

问题


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:

How do I programmatically get the text within each TextBox?


回答1:


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.


来源:https://stackoverflow.com/questions/56943994/how-to-get-the-raw-text-from-a-flutter-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!