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
getBoxesForRangemethod uses character indices from the original text string used to build the paragraph.0starts at the first character, andtotalTextLengthends 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
boxeslist and check the corresponding text segment or box dimensions. - Ensure you account for every
addTextcall—each contributes to the total length, regardless of styling applied withpushStyle/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
getBoxesForRangeoperates).
内容的提问来源于stack exchange,提问作者AVEbrahimi
相关产品推荐
相关产品推荐

