如何从Flutter TextBox获取原始文本 [英] How to get the raw text from a Flutter TextBox

查看:233
本文介绍了如何从Flutter TextBox获取原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flutter中,在放置Paragraph或TextPainter的文本后,可以通过调用getBoxesForSelection获取行的Rect(或在行中运行).如果绘制实际的框,它们看起来将像这样:

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);

注意:

更新:

  • 如果要获取整行的文本,则可以立即使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆