gpt4 book ai didi

text - 如何从 Flutter TextBox 中获取原始文本

转载 作者:行者123 更新时间:2023-12-04 12:42:26 25 4
gpt4 key购买 nike

在 Flutter 中,在 Paragraph 或 TextPainter 对文本进行布局后,您可以通过调用 getBoxesForSelection 获取行(或在一行内运行)的 Rects。如果你画出实际的盒子,它们看起来像这样:

enter image description here

如何以编程方式获取每个 TextBox 中的文本?

最佳答案

我希望有更好的方法,但这是目前我找到的唯一方法:

// 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 affinity .
  • 这还不能处理从右到左的文本。

更新:

  • 如果您正在获取整行的文本,您现在可以使用 LineMetrics(来自 TextPainter.computeLineMetrics())而不是 TextBox。这个过程是相似的。

关于text - 如何从 Flutter TextBox 中获取原始文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com