Sub topic 13
Rebuilding efficiently with AnimatedBuilder
This chapter explains how AnimatedBuilder rebuilds only the part of a widget tree that changes on each animation tick. It assumes you know Dart closures and generics, how StatefulWidget and setState work, and what you learned in earlier chapters about AnimationController, tickers, and Tween.
The problem: rebuilding too much
An AnimationController produces a new value on every frame, which is usually 60 or 120 times per second. Something has to turn each value into pixels. The most direct approach is to call setState from a listener on the controller:
_controller.addListener(() => setState(() {}));This works, but it calls build on the whole State object 60 times per second. If that build method creates a large subtree, Flutter allocates new widget objects for all of it on every frame, even though only one small part, such as a rotation angle, actually changes.
AnimatedBuilder solves this. It is a widget that listens to an animation, rebuilds only its own builder output when the value changes, and lets you hand it a pre-built subtree that is reused unchanged.
How AnimatedBuilder works
AnimatedBuilder takes three arguments:
animation: aListenable. This is usually anAnimation<double>or anAnimationController, but anyListenableis accepted.builder: a functionWidget Function(BuildContext context, Widget? child). Flutter calls it every time the listenable notifies.child: an optional widget that is built once and passed back intobuilderas its second argument.
Internally, AnimatedBuilder is a subclass of AnimatedWidget. It subscribes to the listenable in its state object and calls setState on itself when notified. Because the setState happens inside AnimatedBuilder's own state, your outer State object's build method is not called again. Only the builder closure runs.
The diagram below shows the flow of one tick.
A complete example
The spinning square from the topic code shows the pattern:
import 'package:flutter/material.dart';
class SpinningSquare extends StatefulWidget {
const SpinningSquare({super.key});
@override
State<SpinningSquare> createState() => _SpinningSquareState();
}
class _SpinningSquareState extends State<SpinningSquare>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
);
@override
void initState() {
super.initState();
_controller.repeat();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
child: Container(width: 80, height: 80, color: Colors.indigo),
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14159265358979,
child: child,
);
},
);
}
}Follow the pieces in order:
- The
Stateobject mixes inSingleTickerProviderStateMixin, so it can passthisasvsync. - The controller runs for 2 seconds per cycle, and
repeat()restarts it each time it finishes. buildruns once (plus any time the parent rebuilds). It creates theAnimatedBuilderand the indigoContainer.- On each tick, the
builderruns. It reads_controller.value, which goes from 0.0 to 1.0, and converts it to an angle in radians. One full turn is 2π. - The builder returns a fresh
Transform.rotatethat wraps the samechildinstance.
Step 5 is the key point. Flutter sees that the child widget is identical to the one from the previous frame, so it skips rebuilding and re-laying-out that subtree. Only the transform changes, and a transform can be applied at paint time without re-running layout for the child.
The child parameter
The child argument is the most commonly misunderstood part of AnimatedBuilder. Compare two versions of the same builder.
Without child, everything is created inside the builder:
AnimatedBuilder(
animation: _controller,
builder: (context, _) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14159265358979,
child: Container(width: 80, height: 80, color: Colors.indigo),
);
},
)With child, the container is created once:
AnimatedBuilder(
animation: _controller,
child: Container(width: 80, height: 80, color: Colors.indigo),
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14159265358979,
child: child,
);
},
)For a single Container, the difference is negligible. It matters when the static part is expensive, for example a card containing a list, an image, text with several styles, or a deep layout. In the first version, a new copy of that whole subtree is built 60 times per second. In the second, it is built once.
A rule of thumb: anything inside the builder that does not depend on the animation value should move into child.
Scoping: keep the builder small
AnimatedBuilder rebuilds whatever you return from builder. The position of the AnimatedBuilder in the tree therefore decides how much work each tick costs. Wrapping an entire screen in one gives the same cost as calling setState on the screen.
| Placement | Work per tick | Verdict |
|---|---|---|
| Around the whole `Scaffold` | Rebuilds the whole screen | Avoid |
| Around a card that contains the animated part | Rebuilds the card and its children | Acceptable for small cards |
| Around only the widget that uses the value, with static parts passed as `child` | Rebuilds one transform or decoration | Preferred |
Animating with a Tween inside the builder
The controller's value is a double from 0.0 to 1.0. To animate something else, such as a color or a size, map the value with a Tween and pass the resulting Animation to AnimatedBuilder. Reading the mapped animation's value inside the builder keeps the code short:
import 'package:flutter/material.dart';
class ColorShift extends StatefulWidget {
const ColorShift({super.key});
@override
State<ColorShift> createState() => _ColorShiftState();
}
class _ColorShiftState extends State<ColorShift>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<Color?> _color;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..repeat(reverse: true);
_color = ColorTween(begin: Colors.orange, end: Colors.teal)
.animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _color,
builder: (context, _) {
return Container(width: 120, height: 120, color: _color.value);
},
);
}
}Two details are worth noting. First, ColorTween is used instead of Tween<Color>, because Color does not support the + and * operators that the plain Tween needs. ColorTween interpolates with Color.lerp, and its value type is Color?. Second, the _color animation is created once in initState. Creating a new tween or animation inside build would work, but it allocates objects on every parent rebuild for no benefit.
Common errors
- Passing the wrong listenable. If you pass an unrelated object, such as a different controller, the builder never runs when you expect it to. Pass the animation whose value the builder reads.
- Forgetting that
childcan be null. The parameter has typeWidget?. If you omitchildonAnimatedBuilder, the builder receivesnull. Pass it on to a widget that accepts a nullable child only if that is what you meant. - Building the static subtree inside the builder. This compiles and runs, but it silently erases the optimization.
- Calling
setStateinside the builder. The builder runs during the build phase, so callingsetStatethere raises an error. Compute values and return widgets only. - Missing
dispose.AnimatedBuilderremoves its own listener when it is disposed, but it does not dispose your controller. You still need to call_controller.dispose()in yourState.
AnimatedBuilder versus the alternatives
AnimatedBuilder is general. Flutter also ships ready-made widgets that do the same job for common properties, such as FadeTransition, ScaleTransition, and SlideTransition. They are all subclasses of AnimatedWidget, which has the same listening mechanism. Use a built-in transition when one exists for your property. Use AnimatedBuilder when you need to combine several effects in one widget, or when no ready-made transition covers the property you want to change.
A related option is to write your own subclass of AnimatedWidget. This is useful when the same animated widget appears in several places, because you can give it a name and reuse it. For a single use, AnimatedBuilder is shorter.
Exercise
In the SpinningSquare example, the Container is passed as the child argument instead of being created inside the builder. What does this change at runtime, and when does it matter?
Show answer
The Container is built once and the same widget instance is handed to the builder on every tick, so Flutter does not rebuild that subtree on each frame. Only the Transform.rotate that wraps it is recreated. For a single colored box the saving is tiny. It matters when the static subtree is large or expensive, such as a card with text, images, or lists, because otherwise that whole subtree would be rebuilt about 60 times per second.
Exercise
You wrap your whole screen in one AnimatedBuilder to animate a small icon in the app bar. The animation works, but scrolling a long list on the same screen becomes choppy. Why, and how do you fix it?
Show answer
The builder returns the whole screen, so every tick rebuilds the screen, including the list. The fix is to move the AnimatedBuilder so it wraps only the icon's transform, and to pass any static parts as the child argument. The rest of the screen is then no longer rebuilt on each frame.