在Flutter中,在放置Paragraph或TextPainter的文本后,可以通过调用getBoxesForSelection
获取行的Rect(或在行中运行)。如果绘制实际的框,则它们看起来像这样:
如何以编程方式在每个TextBox中获取文本?
答案 0 :(得分:0)
我希望有更好的方法,但这是到目前为止我发现的唯一方法:
// 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);
注意: