text - 如何从 Flutter TextBox 中获取原始文本
问题描述
在 Flutter 中,在 Paragraph 或 TextPainter 布置好文本后,您可以通过调用getBoxesForSelection
. 如果你画出实际的盒子,它们看起来像这样:
如何以编程方式获取每个 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 亲和力。
- 这还不处理从右到左的文本。
更新:
- 如果您正在获取整行的文本,您现在可以使用 LineMetrics (from
TextPainter.computeLineMetrics()
) 而不是 TextBox。该过程将是相似的。
推荐阅读
- templates - 字符串提取:Marklogic 中的 functx:escape-for-regex() 问题
- python - 导入 kivy.core.window 和使用多处理库时的问题
- reactjs - 如何在 React 中获取传递的 props 值
- html - 角反应形式显示
- swiftui - SwiftUI 鼠标 ScrollWheel 事件
- angular - Angular Form Control 返回默认值而不是值
- javascript - 当主线程与其他操作排队时,React 不会在状态更改后重新渲染组件?
- c++ - 为什么不能将作为常量引用传递给函数的数组的 .size() 用作模板参数?
- node.js - 在 nextjs 自定义服务器上保存上传的文件
- python - 熊猫与子集的滚动相关性