Sub topic 11
Drawing text with TextPainter
Canvas has methods for shapes but none for text. To draw a string inside paint(), you use TextPainter. This chapter covers its lifecycle, how to measure and position text, and the edge cases that cause crashes or blurry layouts.
This chapter assumes you can write a CustomPainter with a paint(Canvas, Size) method. It also assumes you know Offset, Size, and TextStyle, and have read the chapters on coordinates and shouldRepaint.
Why a separate object draws text
Laying out text involves line breaking, font fallback, bidirectional scripts, and glyph shaping. Canvas only knows how to draw a ready-made dart:ui Paragraph. TextPainter is the framework helper that builds that paragraph from a TextSpan, measures it, and draws it onto a canvas at an Offset.
A TextPainter is not a CustomPainter. It is a plain helper object that you create and use inside paint().
The three-step lifecycle
Every use follows the same order:
- Create the
TextPainterwith atext(aTextSpan) and atextDirection. - Call
layout()with the width constraints. This measures the text. - Call
paint(canvas, offset). The offset is where the top-left corner of the text box lands.
Here is a helper that draws one line of text centered in the available size:
import 'package:flutter/material.dart';
void paintCenteredLabel(
Canvas canvas,
Size size,
String text,
TextStyle style,
) {
final painter = TextPainter(
text: TextSpan(text: text, style: style),
textDirection: TextDirection.ltr,
textAlign: TextAlign.center,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: size.width);
painter.paint(
canvas,
Offset(
(size.width - painter.width) / 2,
(size.height - painter.height) / 2,
),
);
painter.dispose();
}The offset is computed after layout(), because width and height are only valid once layout has run.
Constraints and what layout() does
layout({double minWidth = 0, double maxWidth = double.infinity}) decides the width of the text box.
| Call | Result |
|---|---|
| `layout()` | No limit. The text stays on one line unless it contains `\n`. |
| `layout(maxWidth: 120)` | Text wraps at 120 logical pixels. The box can be narrower than 120. |
| `layout(minWidth: 120, maxWidth: 120)` | The box is exactly 120 wide, so `textAlign` has room to work. |
The last row matters for alignment. With only maxWidth, the box shrinks to fit the text. TextAlign.center then has nothing to center within, and your own offset math does the centering. To have textAlign position lines inside a fixed box, pass equal minWidth and maxWidth.
Measuring text
After layout(), these members describe the result:
| Member | Meaning |
|---|---|
| `width`, `height`, `size` | The size of the laid-out box in logical pixels |
| `didExceedMaxLines` | `true` if `maxLines` forced truncation |
| `computeLineMetrics()` | A list of per-line data: baseline, ascent, descent, width |
| `computeDistanceToActualBaseline(TextBaseline.alphabetic)` | Distance from the top of the box to the baseline |
| `getPositionForOffset(Offset)` | The character position under a point, useful for tap handling |
Measure before you draw whenever the text must fit something. A common case is a chart label that has to stay clear of a neighboring bar.
Styled spans and text scaling
A TextSpan can hold children, each with its own style, so one painter can draw a large number next to a small unit. The painter below also accepts a TextScaler, which carries the user's system font-size setting. TextScaler needs Flutter 3.16 or later.
A painter has no BuildContext, so the widget reads the scaler and theme style and passes them in. Both go into shouldRepaint, so a change to the system font size triggers a repaint.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class ValueRingPainter extends CustomPainter {
ValueRingPainter({
required this.value,
required this.textStyle,
required this.textScaler,
});
final double value; // 0.0 to 1.0
final TextStyle textStyle;
final TextScaler textScaler;
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final rect = Rect.fromCircle(
center: center,
radius: size.shortestSide / 2 - 8,
);
final ring = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 8;
canvas.drawArc(rect, 0, 2 * math.pi, false, ring..color = Colors.grey.shade300);
canvas.drawArc(
rect,
-math.pi / 2,
2 * math.pi * value,
false,
ring
..color = Colors.teal
..strokeCap = StrokeCap.round,
);
final label = TextPainter(
text: TextSpan(
children: [
TextSpan(
text: '${(value * 100).round()}',
style: textStyle.copyWith(fontSize: 40, fontWeight: FontWeight.bold),
),
TextSpan(text: '%', style: textStyle.copyWith(fontSize: 16)),
],
),
textDirection: TextDirection.ltr,
textScaler: textScaler,
)..layout();
label.paint(canvas, center - Offset(label.width / 2, label.height / 2));
label.dispose();
}
@override
bool shouldRepaint(covariant ValueRingPainter oldDelegate) =>
oldDelegate.value != value ||
oldDelegate.textStyle != textStyle ||
oldDelegate.textScaler != textScaler;
}
class ValueRing extends StatelessWidget {
const ValueRing({super.key, required this.value});
final double value;
@override
Widget build(BuildContext context) {
return CustomPaint(
size: const Size(160, 160),
painter: ValueRingPainter(
value: value,
textStyle: Theme.of(context).textTheme.bodyMedium!,
textScaler: MediaQuery.textScalerOf(context),
),
);
}
}
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: ValueRing(value: 0.72))),
),
);The ring is fixed at 160 by 160, but the text grows with the system setting. If the text must stay inside a fixed area, measure it and shrink the fontSize until label.width fits.
Rotated text
Text is drawn along the x-axis. To draw a vertical axis label, rotate the canvas around the anchor point and draw the text centered on the origin. Use save() and restore() so the rotation does not affect later drawing.
import 'dart:math' as math;
import 'package:flutter/material.dart';
void paintRotatedLabel(
Canvas canvas,
Offset anchor,
String text,
TextStyle style,
) {
final painter = TextPainter(
text: TextSpan(text: text, style: style),
textDirection: TextDirection.ltr,
)..layout();
canvas.save();
canvas.translate(anchor.dx, anchor.dy);
canvas.rotate(-math.pi / 2); // reads bottom to top
painter.paint(canvas, Offset(-painter.width / 2, -painter.height / 2));
canvas.restore();
painter.dispose();
}Rotation happens around the translated origin, so the offset passed to paint() is relative to the anchor, not to the canvas corner.
Cost, caching, and disposal
layout() is the expensive step. It shapes glyphs and breaks lines, while paint() is comparatively cheap. A painter that creates and lays out a TextPainter on every frame is fine for a few labels that change rarely. It becomes a problem when you draw hundreds of labels or animate at 60 or 120 frames per second.
- Create
TextPainterobjects ahead of time, for example in the widget'sState, and rebuild them only when the string, style, or scaler changes. - Do not change
textor constraints insidepaint()for text that is static. Settingtextto a new span invalidates the layout. - If the same
TextPainteris reused across frames, calllayout()again only when its inputs change. Eachpaint()call needs a valid layout. - Call
dispose()when you are finished with aTextPainter. It holds a native paragraph object. Painters created and used inside onepaint()call can be disposed at the end of that call. Painters stored inStateare disposed inState.dispose().
Common errors
- Text is invisible. The style has no color and the background is dark, or the offset puts the text outside the canvas. Print
painter.sizeand your offset to check. - Text is clipped or wraps unexpectedly. The
maxWidthyou passed is smaller than the text needs. UsemaxLineswithellipsisto control overflow, and checkdidExceedMaxLines. textAlignseems to do nothing. The box shrank to the text width. PassminWidthequal tomaxWidth.- Text looks wrong in right-to-left languages. You hard-coded
TextDirection.ltr. Read the direction fromDirectionality.of(context)in the widget and pass it to the painter. - Labels do not update. The painter's
shouldRepaintignores the new text or style.
Exercise
A painter draws the label "Revenue" with TextPainter(...)..layout(maxWidth: 200) and textAlign: TextAlign.right. The text still appears at the left edge of the 200-pixel area. Why, and what is the fix?
Show answer
With only maxWidth, the laid-out box shrinks to the width of the text, so right alignment has no extra room and the box is painted at the offset you gave, such as Offset.zero. Pass minWidth: 200 as well, so the box is exactly 200 wide and textAlign can push the text to the right. Alternatively, keep the shrunken box and compute the offset as Offset(200 - painter.width, 0).
Exercise
A ValueRingPainter ignores the user's larger system font setting after the setting is changed while the app is running. Which two places in the code need to handle textScaler?
Show answer
The painter must pass textScaler to the TextPainter constructor so the text is laid out at the scaled size. Its shouldRepaint must also compare oldDelegate.textScaler != textScaler. Without that comparison, Flutter reuses the old frame and skips paint().