You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:如何获取渲染单词盒子列表并确定getBoxesForRange的maxRange?

How to Determine maxRange for getBoxesForRange to Get All Rendered Word Boxes

To get the complete list of boxes for all rendered text in your Paragraph, the maxRange parameter should be set to the total number of characters in the text content you built with the ParagraphBuilder. Here's how to do this properly:

Step 1: Track the Total Text Length as You Build

Since the Paragraph object doesn’t expose the original text length directly, you need to calculate it while adding content to the ParagraphBuilder. Modify your code to accumulate the length of every piece of text you add:

var pin = Offset(0, 0);
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
  ui.ParagraphStyle(
    textDirection: ui.TextDirection.rtl,
    textAlign: ebookTextAlign,
    fontFamily: "Asan",
    fontSize: ebookMainTextSize,
  ),
)..pushStyle(ui.TextStyle(color: const ui.Color(0xFF000000)));

// Track total text length as we add content
int totalTextLength = 0;

spans.forEach((spn) {
  if (spn.localName == "p") {
    builder.addText("\n");
    totalTextLength += 1; // Account for the newline character
  }
  final textToAdd = spn.text + " ";
  builder.addText(textToAdd);
  totalTextLength += textToAdd.length; // Add length of span text plus trailing space
});

builder.pop();
paragraph = builder.build()
  ..layout(ui.ParagraphConstraints(width: size.width));

var list = new List<ExtendedTextBox>();
// Use the calculated total length as maxRange
var boxes = paragraph.getBoxesForRange(0, totalTextLength);

Key Notes:

  • The getBoxesForRange method uses character indices from the original text string used to build the paragraph. 0 starts at the first character, and totalTextLength ends at the last character (since the end index is exclusive).
  • This includes all characters you added: text from spans, newlines, and trailing spaces. If you later want to filter out boxes for whitespace (like spaces or newlines), you can iterate through the boxes list and check the corresponding text segment or box dimensions.
  • Ensure you account for every addText call—each contributes to the total length, regardless of styling applied with pushStyle/pop.

Edge Cases to Consider:

  • If you have zero-width or invisible characters, their boxes will still be included unless you explicitly exclude them from the total length calculation.
  • If your text includes emojis or multi-byte characters, the length calculation still works because it counts each Unicode character as a single index (which matches how getBoxesForRange operates).

内容的提问来源于stack exchange,提问作者AVEbrahimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:09:41