Skip to content

Commit 3295a48

Browse files
Avoid calling TextPainter.plainText for simple static text (#146084)
`InlineSpan.toPlainText` is surprisingly expensive even for a simple `TextSpan` like `TextSpan(text: 'AAA', children: [TextSpan(text: char * 10), TextSpan(text: char * 20)])` ![image](https://github.com/flutter/flutter/assets/31859944/60014acb-78bd-4dbb-a48d-74295aeb612c)
1 parent bf7deff commit 3295a48

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

packages/flutter/lib/src/painting/text_painter.dart

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,14 @@ class _UntilTextBoundary extends TextBoundary {
276276
}
277277

278278
class _TextLayout {
279-
_TextLayout._(this._paragraph, this.writingDirection, this.rawString);
279+
_TextLayout._(this._paragraph, this.writingDirection, this._painter);
280280

281281
final TextDirection writingDirection;
282-
final String rawString;
282+
283+
// Computing plainText is a bit expensive and is currently not needed for
284+
// simple static text. Pass in the entire text painter so `TextPainter.plainText`
285+
// is only called when needed.
286+
final TextPainter _painter;
283287

284288
// This field is not final because the owner TextPainter could create a new
285289
// ui.Paragraph with the exact same text layout (for example, when only the
@@ -340,6 +344,7 @@ class _TextLayout {
340344
/// line ended with a line feed.
341345
late final _LineCaretMetrics _endOfTextCaretMetrics = _computeEndOfTextCaretAnchorOffset();
342346
_LineCaretMetrics _computeEndOfTextCaretAnchorOffset() {
347+
final String rawString = _painter.plainText;
343348
final int lastLineIndex = _paragraph.numberOfLines - 1;
344349
assert(lastLineIndex >= 0);
345350
final ui.LineMetrics lineMetrics = _paragraph.getLineMetricsAt(lastLineIndex)!;
@@ -1189,7 +1194,7 @@ class TextPainter {
11891194
// called.
11901195
final ui.Paragraph paragraph = (cachedLayout?.paragraph ?? _createParagraph(text))
11911196
..layout(ui.ParagraphConstraints(width: layoutMaxWidth));
1192-
final _TextLayout layout = _TextLayout._(paragraph, textDirection, plainText);
1197+
final _TextLayout layout = _TextLayout._(paragraph, textDirection, this);
11931198
final double contentWidth = layout._contentWidthFor(minWidth, maxWidth, textWidthBasis);
11941199

11951200
final _TextPainterLayoutCacheWithOffset newLayoutCache;

0 commit comments

Comments
 (0)