Sub topic 7
Deciding when to repaint with shouldRepaint
This chapter covers how Flutter decides whether to call paint() again, and how to write shouldRepaint so it is correct and cheap. It assumes you can write a CustomPainter subclass, you know what Canvas and Paint are, and you understand that a widget's build method can run many times. The following chapter covers animation-driven repainting.
What shouldRepaint is for
A CustomPainter can be asked to draw many times during an app's life. Drawing can be expensive, so Flutter avoids redrawing when nothing changed. shouldRepaint is the method that tells Flutter whether the new painter would draw something different from the old one.
The signature is:
bool shouldRepaint(covariant CustomPainter oldDelegate)You must implement it. It has no default body, so a painter that omits it will not compile. The parameter oldDelegate is the painter that CustomPaint held before the current rebuild. The covariant keyword lets you narrow its type to your own painter class, so you can read your own fields without a cast.
When Flutter calls it
shouldRepaint is called only when a CustomPaint widget is rebuilt with a new painter instance. Flutter then compares the two instances in this order:
- If the new painter is the same object as the old one (
identical), nothing is called and nothing repaints. - If the runtime types differ, Flutter repaints without asking you.
- Otherwise Flutter calls
newPainter.shouldRepaint(oldPainter). If it returnstrue, the render object is marked as needing paint.
The method is not called on every frame. It is called once per rebuild that supplies a new painter. If nothing rebuilds the CustomPaint, shouldRepaint never runs, and the canvas contents stay as they were.
The same method also runs for foregroundPainter, with the same rules, because the widget treats both painters in the same way.
flowchart TDThe diagram below shows the decision as a whole.
Returning false for painters with no data
A painter that has no fields draws the same picture every time. For that case you can return false safely:
import 'package:flutter/material.dart';
class CirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.teal
..style = PaintingStyle.fill;
canvas.drawCircle(size.center(Offset.zero), size.shortestSide / 2, paint);
}
@override
bool shouldRepaint(covariant CirclePainter oldDelegate) => false;
}Returning false does not stop the circle from being drawn the first time, and it does not stop a repaint caused by other things, such as a layout size change. It only says that a new CirclePainter instance adds no reason to repaint.
Comparing the fields that affect drawing
When the painter holds data, compare every field that paint() reads. The progress ring is a good example, because it has one input:
import 'dart:math' as math;
import 'package:flutter/material.dart';
class ProgressRingPainter extends CustomPainter {
ProgressRingPainter({required this.progress});
final double progress; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
final track = Paint()
..color = Colors.grey.shade300
..style = PaintingStyle.stroke
..strokeWidth = 12;
final bar = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 12
..strokeCap = StrokeCap.round;
final arcRect = rect.deflate(6);
canvas.drawArc(arcRect, 0, 2 * math.pi, false, track);
canvas.drawArc(arcRect, -math.pi / 2, 2 * math.pi * progress, false, bar);
}
@override
bool shouldRepaint(covariant ProgressRingPainter oldDelegate) =>
oldDelegate.progress != progress;
}A parent widget creates a new ProgressRingPainter each time it rebuilds. If the parent rebuilds because of some unrelated state change, progress is the same, shouldRepaint returns false, and the ring is not redrawn. When progress changes, it returns true.
With several fields, combine the comparisons with ||:
@override
bool shouldRepaint(covariant DotPainter oldDelegate) =>
oldDelegate.center != center || oldDelegate.radius != radius;A common rule is to compare exactly the fields that paint() reads. A field that is never read during painting does not need to be compared.
Common errors
Always returning false when the painter has data
This is the most frequent bug. The painter has a progress field, shouldRepaint returns false, and the ring never updates after its first paint. Because the parent rebuilds with a new value, the code looks right, but Flutter is told that nothing changed. If a painter has fields and the picture does not update, check this method first.
Always returning true
Returning true unconditionally is correct but wasteful. Every parent rebuild forces a full repaint, even when the drawing is identical. For a small painter this is harmless. For a large drawing, such as a chart with thousands of points, it costs frame time for no visible change. It is acceptable as a starting point when you are unsure, and you can tighten it after you profile.
Forgetting a field
If paint() reads three fields and shouldRepaint compares two, the third will update only when something else triggers a repaint. This produces bugs that appear intermittently, which makes them hard to trace. Add the new comparison at the same time as you add the field.
Comparing mutable objects by identity
Suppose the painter takes a List<double> points. If the caller mutates the same list and passes it again, oldDelegate.points != points is false, because both painters hold the same list object. The comparison sees no difference even though the contents changed. You have two options:
- Pass a new list each time and compare with a deep check such as
listEqualsfrompackage:flutter/foundation.dart. - Keep data immutable, and create a new list whenever the data changes.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class LinePlotPainter extends CustomPainter {
LinePlotPainter({required this.points});
final List<double> points; // treat as immutable
@override
void paint(Canvas canvas, Size size) {
if (points.length < 2) return;
final path = Path()..moveTo(0, size.height * (1 - points.first));
for (var i = 1; i < points.length; i++) {
final x = size.width * i / (points.length - 1);
path.lineTo(x, size.height * (1 - points[i]));
}
canvas.drawPath(
path,
Paint()
..color = Colors.green
..style = PaintingStyle.stroke
..strokeWidth = 2,
);
}
@override
bool shouldRepaint(covariant LinePlotPainter oldDelegate) =>
!listEquals(oldDelegate.points, points);
}listEquals walks both lists, so its cost grows with the list length. For very long lists, consider a version number instead: pass an int revision that the owner increments on each change, and compare that.
Reading state that is not a field
If paint() reads a global variable, a singleton, or a value from an object that the painter does not own, shouldRepaint cannot see a change in it. Put every input in the painter's constructor so it can be compared.
What shouldRepaint does not control
shouldRepaint answers one question: does a new painter instance need a repaint? It does not control all repaints.
- A change in the size given to the painter repaints it, because layout marks the render object as needing paint.
- A
repaintlistenable passed tosuper(repaint: ...)triggers repaints directly, without a rebuild and without callingshouldRepaint. The next chapter shows this. - If an ancestor
RepaintBoundaryrepaints, the content inside it may be repainted for reasons unrelated to your painter.
So shouldRepaint returning false is a statement about the painter's data. It is not a guarantee that paint() will never run again.
Writing paint() so the answer stays simple
Correct shouldRepaint logic depends on paint() being a pure function of the painter's fields and the Size. Follow these habits:
- Do not store drawing results in mutable fields during
paint(). - Do not read the current time or random numbers inside
paint(). If you need them, make them input fields, or feed them through an animation. - Do not call
setStateor trigger a rebuild frompaint().
When paint() depends only on its inputs, the comparison in shouldRepaint is a complete description of when the picture can change.
Choosing a strategy
| Painter situation | Recommended `shouldRepaint` |
|---|---|
| No fields, fixed drawing | `false` |
| A few value fields (numbers, colors, offsets) | Compare each field with `!=` |
| A list or map of data | Compare with `listEquals` or `mapEquals`, or use a revision number |
| Unsure, or the drawing is cheap | `true`, then refine after profiling |
| Driven by an `Animation` through `repaint` | Compare the animation reference, as in the spinner example |
You can test your implementation without a device. Create two painter instances and call the method directly:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('repaints only when progress changes', () {
final a = ProgressRingPainter(progress: 0.5);
final same = ProgressRingPainter(progress: 0.5);
final changed = ProgressRingPainter(progress: 0.8);
expect(same.shouldRepaint(a), isFalse);
expect(changed.shouldRepaint(a), isTrue);
});
}This test assumes ProgressRingPainter is imported from the file where it is defined. Such tests are cheap, and they catch the "forgot a field" error whenever you add a field later.
Exercise
A painter has fields color and strokeWidth, and paint() uses both. Its shouldRepaint is oldDelegate.color != color. A parent changes only strokeWidth and rebuilds. What happens on screen, and how do you fix the method?
Show answer
The line keeps its old width, because shouldRepaint returns false and Flutter keeps the previous drawing. The fix is to compare both fields: oldDelegate.color != color || oldDelegate.strokeWidth != strokeWidth.
Exercise
Why is shouldRepaint not called on every frame of a running animation that uses super(repaint: animation)?
Show answer
The repaint listenable marks the render object as needing paint directly on each tick. No new painter is supplied by a rebuild, so there is no old and new painter to compare, and shouldRepaint is not involved.