Sub topic 6
Cache Static Subtrees with the Builder Child Parameter
This chapter assumes you know how setState and build work, can read basic Dart, and have seen the earlier chapters on limiting setState scope and using const widgets. Here you will learn how the child parameter of builder widgets lets you keep a static subtree out of a rebuild, even when the builder function runs often.
The problem: a builder that rebuilds everything inside it
Many Flutter widgets take a builder function: AnimatedBuilder, ValueListenableBuilder, ListenableBuilder, TweenAnimationBuilder, Consumer from package:provider, and others. The framework calls that function again whenever the data it watches changes. For an animation, that can mean 60 or 120 calls per second.
Whatever you create inside the builder function is created again on every call. Consider a rotating card:
import 'package:flutter/material.dart';
class SpinningCard extends StatefulWidget {
const SpinningCard({super.key});
@override
State<SpinningCard> createState() => _SpinningCardState();
}
class _SpinningCardState extends State<SpinningCard>
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 AnimatedBuilder(
animation: _controller,
builder: (context, _) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14159,
// Rebuilt on every animation tick.
child: Card(
child: Column(
children: [
Text('Title', style: Theme.of(context).textTheme.titleLarge),
const Text('A long description that never changes.'),
],
),
),
);
},
);
}
}The Card and its Column do not depend on the animation. Only the rotation angle does. Yet the builder creates new Card, Column, and Text widget objects on every tick, and the framework must compare them with the previous ones.
How the child parameter works
Builder widgets that support caching accept a child argument. You build that subtree once, outside the builder function, and the widget passes it back to you as the last argument of the builder. The AnimatedBuilder signature is Widget Function(BuildContext context, Widget? child). ValueListenableBuilder uses (context, value, child).
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
// Built once per call to this State's build method.
child: Card(
child: Column(
children: [
Text('Title', style: Theme.of(context).textTheme.titleLarge),
const Text('A long description that never changes.'),
],
),
),
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14159,
child: child,
);
},
);
}On each animation tick, the builder runs again and returns a new Transform.rotate. That new widget holds the same child instance as before. When the framework updates the element for the child, it finds the new widget is identical to the old one (identical(oldWidget, newWidget)) and stops there. It does not call build on anything inside that subtree.
The rule the framework follows is this: when it updates an element with a new widget, and the new widget is the identical object to the one the element already holds, it skips the update. This is the same mechanism that makes const widgets cheap. The child parameter gives you the same result for widgets that cannot be const because they depend on runtime values such as Theme.of(context).
The diagram below shows what happens on each tick.
Using child with ValueListenableBuilder
The same pattern applies to ValueListenableBuilder, where the builder runs whenever the notifier's value changes:
final ValueNotifier<int> likes = ValueNotifier<int>(0);
Widget buildLikeBadge() {
return ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, child) {
return Row(
children: [
Text('$value'),
child!,
],
);
},
child: const Icon(Icons.favorite),
);
}The child argument is nullable in the builder signature because you may omit it. If you always pass one, using child! is fine. If you may omit it, handle null.
Here the icon is const, so the child parameter adds little: a const widget created inside the builder would be the same instance anyway. The parameter pays off when the static subtree is large or cannot be const. In that case, pass the subtree as child.
Where to put the cached subtree
The cached child is built in the scope that surrounds the builder widget. It is created each time that outer scope's build method runs. So caching helps against the inner, high-frequency rebuilds (animation ticks, notifier changes) and not against rebuilds of the outer widget.
Two consequences follow:
- If the outer
StatecallssetState, the child expression runs again and produces a new instance. The framework then rebuilds the child subtree once, as normal. This is expected. - The child can use
BuildContextfrom the outerbuild. In the example above,Theme.of(context)registers a dependency of the outer widget on the theme, not of the builder.
If you need the child to be stable even across outer rebuilds, make it const or move it into its own widget class with a const constructor, as covered in the earlier chapters.
What goes in the child and what stays in the builder
Use a simple test. For each widget in the builder, ask whether its configuration depends on the value the builder reacts to.
| Widget in the subtree | Depends on the changing value? | Where it belongs |
|---|---|---|
| `Transform.rotate` with the animation angle | Yes | Builder |
| `Text('$value')` showing a counter | Yes | Builder |
| `Card` with fixed text and images | No | `child` |
| A large `Column` of unrelated settings rows | No | `child` |
| A `ListView` the user scrolls independently | No | `child` |
Keep the builder as small as possible. The widgets in it should be only the ones that must change, wrapped around the cached child.
Wrapping order matters
Place the changing widget as the outermost layer and the static subtree as its descendant, because the builder returns a single widget tree that contains child. If the static subtree sits above the changing part, you cannot reach it from inside the builder, and you would have to split your widget instead.
For example, to fade an entire panel you wrap the panel:
AnimatedBuilder(
animation: _fade,
child: const SettingsPanel(),
builder: (context, child) {
return Opacity(opacity: _fade.value, child: child);
},
)When the changing part is in the middle of a tree, with static widgets both above and below it, put the builder around only the middle part, and pass the lower static part as child. The upper part stays outside the builder and is not touched.
Common mistakes
- Ignoring the child argument. You pass
child:but build a fresh subtree in the builder anyway. The cache is never used. Search the builder body for widgets that do not depend on the animation or value. - Creating the child inside the builder. Writing
constor a constructor call inside the builder gives no benefit unless it isconst. A non-constconstructor call creates a new object on every run. - Passing
childand then wrapping it in something that depends on a changing value in a way that forces the child to rebuild. The child itself is not rebuilt, but if you place it in a parent that changes its constraints, it may need to be laid out again. Layout is a separate cost from building. Rebuild skipping does not stop relayout or repaint. - Assuming the cached child never updates. If the outer widget rebuilds with new data, the child is rebuilt. If the child shows data that should update from the builder's value, it does not belong in
child. - Forgetting the null check. In
ValueListenableBuilderandAnimatedBuilder,childisWidget?. Usingchild!when you did not pass a child throws a null check error.
Verifying the effect
Do not assume the cache works. Check it with the tools from the measuring chapter. Set debugPrintRebuildDirtyWidgets = true in a debug build and watch the console while the animation runs. Before the change, the card's Column and Text widgets show up in every frame. After the change, only the animated widget and the elements under the builder that actually changed appear. You can also use the Flutter DevTools rebuild counts in the Performance view, which are available in profile mode and debug mode depending on your tooling version.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
// Debug builds only: prints the widgets that are rebuilt in each frame.
debugPrintRebuildDirtyWidgets = true;
runApp(const MaterialApp(home: Scaffold(body: Center(child: SpinningCard()))));
}Run this with the cached version of SpinningCard. You should see the AnimatedBuilder listed on each frame, and the Card subtree listed once at startup and not on later ticks.
Keep in mind that a rebuild count is only a proxy. A rebuild of a few small widgets costs microseconds. Use the cache where the static subtree is large, where the builder fires at animation rates, or where a profile shows build time near the frame budget.
When not to bother
Skip the parameter when:
- The subtree is a handful of widgets and is already
const. - The builder runs rarely, for example once when a user taps a button.
- The static part is so small that passing it through adds more code than it saves.
The parameter is a precise tool for a specific shape: a high-frequency builder wrapped around a larger subtree that does not change.
Exercise
A ValueListenableBuilder<int> shows a counter at the top of a panel and contains a Column with a 40-row static settings list under the counter. The whole Column is created in the builder, and the counter updates every 100 ms. Describe how to restructure the code so the settings list is not rebuilt on counter changes, and say what would still cause it to rebuild.
Show answer
Create the settings list as a widget outside the builder and pass it with the child: argument. Inside the builder, return a Column that holds Text('$value') and the child!. Each counter change then rebuilds the Column and Text, and the framework skips the settings list because the child instance is identical. The list is rebuilt when the outer widget's build method runs again, for example after a setState in the parent, because that creates a new child instance. Making the list a const widget class would avoid even that.
Exercise
You add child: to an AnimatedBuilder, but debugPrintRebuildDirtyWidgets still prints the static subtree on every frame. Name two likely causes.
Show answer
First, the builder may ignore its child argument and build a fresh subtree itself, so the cached instance is never used. Second, the subtree may be placed under a part of the tree that is recreated each frame with a different key or widget type, which makes the framework replace the element instead of updating it. Another possible cause is that the outer widget is itself rebuilding every frame, such as through a parent setState, which creates a new child instance each time.