如何从 Flutter TextBox 中获取原始文本 [英] How to get the raw text from a Flutter TextBox
本文介绍了如何从 Flutter TextBox 中获取原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Flutter 中,在 Paragraph 或 TextPainter 布置文本后,您可以通过调用 getBoxesForSelection
获取行(或在一行内运行)的 Rects.如果您绘制实际的框,它们看起来像这样:
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:
如何以编程方式获取每个 TextBox 中的文本?
How do I programmatically get the text within each TextBox?
推荐答案
我希望有更好的方法,但这是我目前找到的唯一方法:
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);
注意事项:
- 为了更可靠,这应该检查 TextPosition 关联.
- 这还不能处理从右到左的文本.
更新:
- 如果您要获取整行的文本,现在可以使用 LineMetrics(来自
TextPainter.computeLineMetrics()
)而不是 TextBox.过程类似.
- 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.
这篇关于如何从 Flutter TextBox 中获取原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文