Text 如何从颤振文本框中获取原始文本
在flatter中,在段落或文本绘制器布局文本后,可以通过调用getBoxesForSelection获取行或行内运行的矩形。如果绘制实际框,它们看起来像这样:Text 如何从颤振文本框中获取原始文本,text,flutter,typography,Text,Flutter,Typography,在flatter中,在段落或文本绘制器布局文本后,可以通过调用getBoxesForSelection获取行或行内运行的矩形。如果绘制实际框,它们看起来像这样: 如何以编程方式获取每个文本框中的文本?我希望有更好的方法,但这是迄今为止我找到的唯一方法: // The TextPaint has already been laid out // select everything TextSelection selection = TextSelection(baseOffset: 0, ext
如何以编程方式获取每个文本框中的文本?我希望有更好的方法,但这是迄今为止我找到的唯一方法:
// 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);
注:
为了得到更多的反驳,这应该检查。
这还不能处理从右到左的文本。
更新:
如果您正在获取整行的文本,则可以使用TextPainter.computeLineMetrics中的LineMetrics,而不是TextBox。过程也将类似。