Sub topic 8
Animating a painter with the repaint listenable
This chapter assumes you can write a CustomPainter with paint and shouldRepaint, and that you know how to create and dispose an AnimationController. It shows how to animate a painter without rebuilding any widgets, and what can go wrong.
Two ways to animate a painter
The first approach is to wrap CustomPaint in an AnimatedBuilder (or call setState on every tick). Each tick rebuilds the widget, creates a new painter, and Flutter calls shouldRepaint to decide whether to paint. This works, but it runs the build phase 60 or more times per second for a widget whose only change is pixels.
The second approach is to hand the animation to the painter itself. CustomPainter has a constructor parameter repaint that takes a Listenable. CustomPainter extends Listenable, and the render object listens to the painter. When your animation notifies, the painter notifies, and Flutter marks only the paint phase as dirty. No build and no layout happen.
| Aspect | `AnimatedBuilder` + new painter | `super(repaint: animation)` |
|---|---|---|
| Build phase per tick | Yes | No |
| Layout per tick | Only if constraints change | No |
| Paint per tick | If `shouldRepaint` returns true | Always (the notification forces it) |
| `shouldRepaint` consulted per tick | Yes | No |
| Code size | Larger | Smaller |
The spinner example
The painter below receives an Animation<double>, passes it to super(repaint: ...), and reads animation.value inside paint.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class SpinnerPainter extends CustomPainter {
SpinnerPainter(this.animation) : super(repaint: animation);
final Animation<double> animation;
@override
void paint(Canvas canvas, Size size) {
canvas.save();
canvas.translate(size.width / 2, size.height / 2);
canvas.rotate(animation.value * 2 * math.pi);
canvas.drawRect(
Rect.fromCenter(center: Offset.zero, width: 80, height: 80),
Paint()..color = Colors.orange,
);
canvas.restore();
}
@override
bool shouldRepaint(covariant SpinnerPainter oldDelegate) =>
oldDelegate.animation != animation;
}
class Spinner extends StatefulWidget {
const Spinner({super.key});
@override
State<Spinner> createState() => _SpinnerState();
}
class _SpinnerState extends State<Spinner> with SingleTickerProviderStateMixin {
late final AnimationController _controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2))..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CustomPaint(size: const Size(200, 200), painter: SpinnerPainter(_controller));
}
}_SpinnerState.build runs once. Every later frame calls only SpinnerPainter.paint. The canvas.save() and canvas.restore() pair keeps the translate and rotate from leaking into anything drawn after this painter.
What happens on each tick
When the widget is first attached, RenderCustomPaint calls addListener on the painter. When the widget is rebuilt with a different painter object, it removes the listener from the old painter and adds one to the new painter. Then it calls shouldRepaint once to decide whether the new painter needs a paint. So shouldRepaint still matters when the parent rebuilds. It is just not part of the per-tick path.
Passing extra inputs
Real painters mix animated values with ordinary configuration, such as a color. Put the animation in repaint and compare the plain inputs in shouldRepaint.
import 'package:flutter/material.dart';
class PulsePainter extends CustomPainter {
PulsePainter({required this.animation, required this.color})
: super(repaint: animation);
final Animation<double> animation;
final Color color;
@override
void paint(Canvas canvas, Size size) {
final t = Curves.easeOut.transform(animation.value);
final radius = size.shortestSide / 2 * t;
final paint = Paint()
..color = Color.lerp(color, Colors.transparent, t)!
..style = PaintingStyle.stroke
..strokeWidth = 4;
canvas.drawCircle(size.center(Offset.zero), radius, paint);
}
@override
bool shouldRepaint(covariant PulsePainter oldDelegate) =>
oldDelegate.animation != animation || oldDelegate.color != color;
}
class PulseDemo extends StatefulWidget {
const PulseDemo({super.key, this.color = Colors.teal});
final Color color;
@override
State<PulseDemo> createState() => _PulseDemoState();
}
class _PulseDemoState extends State<PulseDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1500),
)..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
child: CustomPaint(
size: const Size(200, 200),
painter: PulsePainter(animation: _controller, color: widget.color),
),
);
}
}
void main() {
runApp(const MaterialApp(home: Scaffold(body: Center(child: PulseDemo()))));
}Here animation.value runs from 0 to 1 and repeats. The curve is applied inside paint, not in the controller, so the controller stays linear and you can reuse it.
If the parent changes color, the parent rebuilds and creates a new PulsePainter. shouldRepaint sees the different color and returns true. If the animation is running, a repaint was coming anyway. If the animation is stopped, this check is the only thing that makes the new color appear.
Listening to more than one source
repaint accepts any Listenable, so you can combine several with Listenable.merge.
import 'package:flutter/material.dart';
class OrbitPainter extends CustomPainter {
OrbitPainter({required this.rotation, required this.scale})
: super(repaint: Listenable.merge([rotation, scale]));
final Animation<double> rotation;
final Animation<double> scale;
@override
void paint(Canvas canvas, Size size) {
// Read rotation.value and scale.value here.
}
@override
bool shouldRepaint(covariant OrbitPainter oldDelegate) =>
oldDelegate.rotation != rotation || oldDelegate.scale != scale;
}A ValueNotifier, a ScrollController, or a TextEditingController works as well. Painting a scroll-linked effect with repaint: scrollController is a common use.
Isolating the repaint
An animation that notifies every frame repaints whatever shares its paint layer. CustomPaint does not create its own layer, so without a boundary your painter may force a repaint of a large surrounding subtree. Wrap animated painters in RepaintBoundary, as PulseDemo does, so that only this widget's layer is repainted per tick. The performance chapter returns to this in more detail.
Common errors
- Reading the value too early. Storing
animation.valuein a field in the constructor freezes the first value. Read the value insidepaint, every time. - Forgetting
repaint. If you pass the animation but skipsuper(repaint: animation), nothing repaints. The painter holds a reference but nobody listens to it. - Creating the controller in
build. Each rebuild creates a new controller, which leaks tickers and restarts the animation. Create it ininitStateor alate finalfield and dispose it. - Missing a
TickerProvidermixin. UseSingleTickerProviderStateMixinfor one controller, andTickerProviderStateMixinfor several. - Calling
setStatefrom a listener. It defeats the point of the pattern by rebuilding the widget on every tick. - Doing heavy work in
paint. The method now runs every frame. Do not allocate large objects or lay out text there when it can be cached. - Comparing the wrong thing in
shouldRepaint. Compare the inputs that affect the drawing. Comparing derived values likeanimation.valueis pointless, since the value changes inside the same animation object.
Choosing between the two approaches
Use repaint when the animation only changes what is drawn. Use AnimatedBuilder when the animation also changes the widget tree around the painter, for example its size or its siblings. A change of size needs layout, and a repaint notification alone does not trigger layout.
Exercise
Your painter passes repaint: _controller to super, and its shouldRepaint always returns false. The animation still runs smoothly. Then a parent rebuild changes the painter's color field, and the color on screen does not update while the animation is paused. Why, and what is the fix?
Show answer
Repaints from the repaint listenable bypass shouldRepaint, so the animation runs even though it returns false. When the parent rebuilds with a new painter, Flutter does consult shouldRepaint, and because it returns false, no repaint is scheduled while the animation is paused. The fix is to compare the changed input: oldDelegate.color != color, and also oldDelegate.animation != animation if the animation can be swapped.
Exercise
A spinner is built with AnimatedBuilder that wraps CustomPaint, creating SpinnerPainter(_controller.value) on every tick. Describe the change needed to use the repaint listenable instead, and name one benefit.
Show answer
Change the painter to take the Animation<double> itself, call super(repaint: animation), and read animation.value inside paint. Then build CustomPaint(painter: SpinnerPainter(_controller)) directly, without AnimatedBuilder. The benefit is that the widget no longer rebuilds each frame, so only the paint phase runs per tick.