Sub topic 13
A repeatable rebuild audit workflow
This chapter ties the earlier techniques into one procedure you can run on any slow screen. It assumes you can read and write StatefulWidget code, know what setState does, and can run an app in profile mode on a real device. It also assumes you have seen the individual tools from earlier chapters: const, extracted widget classes, ValueListenableBuilder, selectors, and narrow MediaQuery accessors.
The core idea is simple. Do not guess. Measure, change one thing, and measure again. Rebuilds are normal and usually cheap, so the goal is not zero rebuilds. The goal is to remove the rebuilds that cost you frame time.
Why a workflow matters
Rebuild tuning goes wrong in predictable ways:
- You "fix" a widget that was never slow, and the code gets harder to read.
- You change five things at once and cannot tell which one helped.
- You measure in debug mode, where timings are far slower and not representative of release.
- You fix a rebuild that was real but cheap, while the actual cost was in layout or paint.
A fixed order of steps prevents these mistakes. Each step produces evidence that decides whether you continue.
Step 1: Define the symptom
Start with something observable. "The feed stutters when I tap Like" is a good symptom. "The screen rebuilds too much" is not, because it does not say whether anyone can feel it.
Write down three things before touching code:
- The exact interaction that is slow (a tap, a scroll, typing in a field).
- The device you test on. Use a mid-range or older physical device, not only a fast emulator.
- The target. For a 60 Hz display, each frame has about 16 ms. For 120 Hz, about 8 ms.
Step 2: Profile in profile mode
Run the app with flutter run --profile. Profile mode keeps enough tooling for DevTools but compiles ahead of time like release, so timings are realistic. Debug mode adds assertions and just-in-time compilation, which can make a screen look much worse than it is.
Open Flutter DevTools and use the Performance view. Interact with the screen and look at the frame chart. Each frame shows a UI thread bar and a raster thread bar.
- A tall UI bar means build, layout, or paint on the Dart side is expensive.
- A tall raster bar means the GPU work is expensive. Reducing rebuilds will not help much here.
This split tells you whether a rebuild audit is the right tool at all. If the raster bar is the problem, go to the repaint chapter instead.
Step 3: Locate the rebuilds
Once the UI thread looks expensive, find out which widgets are rebuilding. There are two complementary tools.
The first is the framework's own log. In a debug build, this prints the widgets rebuilt in each frame:
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
void main() {
// Debug builds only: prints the widgets that are rebuilt in each frame.
debugPrintRebuildDirtyWidgets = true;
runApp(const MyApp());
}Use this log for counting and scope, not for timing. If one tap rebuilds 400 widgets and you expected 5, you have found a scope problem. The numbers are meaningful even though debug timings are not.
The second tool is the Widget rebuild counts in DevTools. When "Track widget rebuilds" is enabled in the Flutter Inspector, it shows how many times each widget in your own code was rebuilt. This is easier to read than a console log on a large screen.
Record the result as a small table. For example:
| Interaction | Widgets rebuilt | UI thread time (profile) |
|---|---|---|
| Tap Like | 412 | 11.8 ms |
| Scroll feed | 38 per frame | 6.1 ms |
| Type in search | 410 | 14.2 ms |
This table becomes your baseline. Every later change is compared against it.
Step 4: Rank the candidates
Not every rebuild deserves attention. Rank them by cost, which is roughly the number of widgets rebuilt multiplied by the work each build does.
Ask these questions about each candidate:
- Is the rebuilt subtree large? A
setStateat the top of a screen rebuilds everything below it that is notconst. - Does the
buildmethod do expensive work, such as sorting, parsing, or creating controllers? - Does the rebuild happen on every frame, such as during an animation or scroll, or only on a rare tap?
- Is a list involved, and are its items built lazily?
A rebuild that happens once per tap and takes 0.3 ms is not worth changing. A rebuild that happens 60 times per second during an animation and covers a big subtree is.
Step 5: Choose one change from the toolbox
Match the cause to the fix. Apply exactly one at a time.
| Cause you found | Fix | Earlier chapter |
|---|---|---|
| `setState` high in the tree rebuilds unrelated children | Move state into a small widget | Limit the scope of `setState` |
| Static children recreated on each build | Add `const` to constructors and instances | Use `const` |
| Large `build` split into helper methods | Extract widget classes | Widget classes versus helper methods |
| Animated or listened widget has a static child | Pass it as the `child` parameter | Builder child caching |
| One value change rebuilds a whole screen | `ValueListenableBuilder` or another `Listenable` builder | Fine-grained listenables |
| Model notifies on any field change | Select a single field | Selecting slices of state |
| Widget rebuilds on keyboard or inset changes | Use `MediaQuery.sizeOf` and similar | Inherited dependencies |
| Long list builds every item | `ListView.builder` with stable keys | Lazy lists and keys |
Here is the most common first fix. The original screen calls setState in a large build, so every tap runs the whole method. The const header and footer survive, but everything else is rebuilt.
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
const ExpensiveHeader(),
Text('Likes: $_likes'),
ElevatedButton(
onPressed: () => setState(() => _likes++),
child: const Text('Like'),
),
const ExpensiveFooter(),
],
);
}
}If the rest of the screen grows beyond a header and footer, moving the counter into its own widget makes the saving much larger:
class LikeCounter extends StatefulWidget {
const LikeCounter({super.key});
@override
State<LikeCounter> createState() => _LikeCounterState();
}
class _LikeCounterState extends State<LikeCounter> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Likes: $_likes'),
IconButton(
icon: const Icon(Icons.favorite),
onPressed: () => setState(() => _likes++),
),
],
);
}
}Now setState marks only _LikeCounterState dirty. The parent screen does not run build at all.
Step 6: Re-measure and compare
After one change, repeat Steps 2 and 3 with the same device, the same interaction, and the same build mode. Add a row to your table.
| Interaction | Before | After |
|---|---|---|
| Tap Like, widgets rebuilt | 412 | 6 |
| Tap Like, UI thread (profile) | 11.8 ms | 2.1 ms |
Compare both numbers. A drop in rebuild count with no change in frame time means the rebuild was cheap and the change was not worth its complexity. In that case consider reverting it.
Run each measurement several times. Frame times vary from run to run, especially on a phone that is warming up or throttling. Look at the typical frames and the worst frames, not a single sample.
Step 7: Decide when to stop
You are done when one of these is true:
- The frames meet your target on your test device.
- The remaining rebuilds are small and cheap.
- The next change would add real complexity for a gain you cannot measure.
Common errors in the audit
- Measuring in debug mode. Debug timings can be several times slower than profile. Use debug only for rebuild counts and the dirty-widget log.
- Changing several things at once. You cannot tell which change helped, and a harmful change can hide behind a helpful one.
- Fixing the wrong layer. A raster-bound frame is not a rebuild problem. Check the thread split first.
- Helper methods that look like widgets. A method such as
_buildHeader()runs inside the parent'sbuild, so it rebuilds whenever the parent does. Extract a class and give it aconstconstructor. - Selectors that return new objects.
context.selectcompares values with==. If the selector returns a new list or object each time without value equality, the widget rebuilds every time. - Ignoring work inside
build. Sorting a list or building a regular expression inbuildcosts time even if the rebuild count is low. Move it out, cache it, or compute it when the data changes. - Forgetting keys on reorderable lists. Without a stable key, state can attach to the wrong item when the list changes.
Putting it together on a large screen
Consider a product screen with a search field, a filter bar, a long product list, and a cart badge. The audit might go like this.
- Symptom: typing in the search field drops frames.
- Profile: UI thread is at 14 ms, raster is fine. Build is the problem.
- Locate: the rebuild log shows about 410 widgets rebuilt per keystroke. The search text lives in the screen's state.
- Rank: the whole screen rebuilds on each keystroke, including the product list.
- Change one thing: keep the search text in a
ValueNotifier<String>and let only the filtered list listen to it through aValueListenableBuilder. - Re-measure: rebuilds drop to the list subtree, and frame time falls under budget.
- Next candidate: the cart badge rebuilds on unrelated model updates. Apply a selector, measure again, and keep the change only if it helps.
Selecting a single field from a model is the typical fix for that last step:
// With package:provider
class UserName extends StatelessWidget {
const UserName({super.key});
@override
Widget build(BuildContext context) {
final name = context.select<UserModel, String>((user) => user.name);
return Text(name);
}
}And the product list should stay lazy, with keys that follow item identity:
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ProductTile(key: ValueKey(item.id), product: item);
},
)Keep a record
A short note per audit pays off later. Record the symptom, the device, the baseline table, the change you made, and the final numbers. When a teammate later asks why a widget is split in an odd way, the note explains it. It also tells you which fixes were worth their cost, so you can apply them earlier on the next screen.
Exercise
A screen drops frames when a user taps a button that increments a counter held in the screen's State. In debug mode, debugPrintRebuildDirtyWidgets shows about 300 widgets rebuilt per tap. List the audit steps you would take, in order, and name the first change you would try and how you would check it worked.
Show answer
First define the symptom (taps drop frames on a named device, target 16 ms). Then run in profile mode and check in DevTools that the UI thread, not the raster thread, is the expensive part. Use the dirty-widget log or rebuild counts to record a baseline (about 300 widgets, plus the UI thread time). Rank the cause: the counter's setState sits high in the tree and rebuilds everything under it. Make one change: move the counter and its button into a small StatefulWidget so setState marks only that subtree dirty, and mark the other children const. Re-measure on the same device in profile mode and compare both the widget count and the UI thread time. If the count falls but frame time does not, the rebuild was cheap, so consider reverting. Stop when the frame target is met.
Exercise
After adding context.select to a widget, you notice it still rebuilds on every model update. The selector is context.select<CartModel, List<Item>>((cart) => cart.items.where((i) => i.inStock).toList()). What is likely wrong and how can you fix it?
Show answer
The selector builds a new List on each call, and lists do not compare equal by contents, so select sees a changed value every time. Fix it by selecting a value with proper equality, such as the count (cart.items.where((i) => i.inStock).length) if the widget only needs that, or by selecting the original list reference and filtering inside build. You can also use a type with value equality. Then confirm with the rebuild log that the widget no longer rebuilds on unrelated updates.
Exercise
You apply a fix and the widget rebuild count falls from 412 to 6, but the UI thread time in profile mode stays at about 3 ms before and after. What do you conclude and what do you do?
Show answer
The original rebuilds were cheap, so the change did not buy measurable frame time. If the change added complexity, revert it and keep the simpler code. Look elsewhere for the actual cost, such as layout, paint, or raster time, or accept that the screen already meets its target.