Sub topic 18
Practical consequences for performance
This chapter assumes you know the three trees from the earlier chapters: widgets are immutable descriptions, elements are the long-lived instances, and render objects do layout and painting. It also assumes you know how setState marks an element dirty and how Widget.canUpdate decides whether an element is reused. Here we turn that model into habits you can apply to everyday code.
Rebuilding is cheap, but its scope is yours to control
Creating a widget allocates a small immutable object. Rebuilding a few hundred of them in one frame is normal. Performance problems usually come from three things:
- A rebuild that reaches far more of the tree than the change needs.
- Expensive work inside
build, such as sorting a list or parsing JSON. - Layout or paint work that is repeated for areas that did not change.
The rule behind the first problem comes from how an element handles its child. When a parent rebuilds, updateChild compares the old child's widget with the new one. If the two are the identical instance, the element returns early. It does not call update or build for that child. If they are different instances with the same type and key, the element is updated and its widget rebuilds. This holds even when every field is equal.
Technique 1: const constructors
A const widget expression is created once at compile time, and every evaluation of it returns the same instance. When a parent rebuilds, the element sees an identical widget and skips that whole subtree, unless something inside it is dirty for its own reasons, such as its own setState or an inherited dependency.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ConstDemo()));
class ConstDemo extends StatefulWidget {
const ConstDemo({super.key});
@override
State<ConstDemo> createState() => _ConstDemoState();
}
class _ConstDemoState extends State<ConstDemo> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
const Padding(
padding: EdgeInsets.all(16),
child: Text('Static header'), // same instance every build
),
Text('Count: $_count'), // new instance every build
ElevatedButton(
onPressed: () => setState(() => _count++),
child: const Text('Add'),
),
],
),
);
}
}The header Padding and the button's Text are skipped on each tap. Only the Text('Count: ...') is rebuilt and updated.
A constructor can only be const if all its fields are final and the arguments are compile-time constants. A widget that takes a runtime value cannot be instantiated as const.
Technique 2: split widgets so setState has a small scope
setState rebuilds the whole subtree below the widget that owns the State, except for const or otherwise identical children. If only one label changes, move that label and its state into its own widget.
import 'package:flutter/material.dart';
class ProductPage extends StatelessWidget {
const ProductPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: const [
ExpensiveGallery(), // not rebuilt when the counter changes
CartCounter(), // owns the state that changes
],
),
);
}
}
class ExpensiveGallery extends StatelessWidget {
const ExpensiveGallery({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 50,
itemBuilder: (context, i) => Center(child: Text('Photo $i')),
),
);
}
}
class CartCounter extends StatefulWidget {
const CartCounter({super.key});
@override
State<CartCounter> createState() => _CartCounterState();
}
class _CartCounterState extends State<CartCounter> {
int _items = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _items++),
child: Text('In cart: $_items'),
);
}
}Prefer a separate widget class over a helper method such as Widget _buildGallery(). A method call runs inside the parent's build every time. A const widget class gives the framework an element it can skip.
Technique 3: keep build cheap and put work elsewhere
Flutter may call build at up to the frame rate, for example during an animation, so build should only describe the UI.
- Compute derived data once, in
initState, indidUpdateWidgetwhen inputs change, or in your state management layer. - Use
ListView.builderorGridView.builderfor long lists. Only the children near the viewport get elements and render objects. - Give list items stable keys when they can be reordered or removed. Without keys, elements are matched by position, so state can attach to the wrong item and elements may be rebuilt needlessly.
Technique 4: repaint boundaries
A RenderObject that repaints marks itself, and painting walks up to the nearest repaint boundary. Everything between that object and the boundary repaints. Without a boundary closer in, the boundary is the root of the layer tree, so a small animation can force a large area to repaint.
RepaintBoundary gives its subtree its own layer. Repainting inside it does not repaint what is outside it, and the reverse also holds.
import 'package:flutter/material.dart';
class BusyScreen extends StatelessWidget {
const BusyScreen({super.key});
@override
Widget build(BuildContext context) {
return const Column(
children: [
RepaintBoundary(
child: CircularProgressIndicator(), // repaints every frame
),
ComplexStaticChart(), // painted once, then reused from its layer
],
);
}
}
class ComplexStaticChart extends StatelessWidget {
const ComplexStaticChart({super.key});
@override
Widget build(BuildContext context) => const SizedBox(height: 300);
}Layout has the same idea. A relayout boundary stops markNeedsLayout from propagating further up, and Flutter adds these automatically in many cases, for example when a render object has tight constraints. You rarely add one by hand.
Choosing the right tool
| Symptom | Likely cause | First fix |
|---|---|---|
| Large subtree rebuilds on a small state change | `setState` too high in the tree | Split into a smaller stateful widget |
| Static children rebuild with their parent | Non-const instances | Add `const` |
| Slow frames while scrolling a long list | Eager list building | Use a `.builder` constructor |
| Whole screen repaints for a small animation | No repaint boundary near the animation | Wrap it in `RepaintBoundary` |
| List items swap state when reordered | Matching by position | Add `ValueKey` |
Measure before you optimize
Use a profile-mode build on a real device, because debug mode is much slower and misleads. In DevTools, the Performance view shows frame times for the UI thread (build, layout, paint) and the raster thread. In debug builds you can also set debugRepaintRainbowEnabled = true from package:flutter/rendering.dart. It tints each repainting layer with a changing color, so you can see which areas repaint on every frame. The DevTools "Track widget rebuilds" option shows the same kind of information for builds.
Exercise
A screen's State class holds int _seconds, updated by a timer every second with setState. Its build returns a Column with a Text('$_seconds') and a non-const HeavyChart(data: _data). Frames are slow once per second. Name two changes that stop HeavyChart from rebuilding on each tick, and say why each works.
Show answer
First, move the timer and _seconds into a small stateful widget that contains only the Text. The parent then never calls setState, so HeavyChart is not rebuilt. Second, if HeavyChart and its arguments can be const, write const HeavyChart(...). Then the same instance is passed on each rebuild, and updateChild skips it. Because data: _data is not a compile-time constant, the first change is the one that applies here. Wrapping the chart in a RepaintBoundary would only help if it also repainted every second, and it would not prevent the rebuild.