Sub topic 3
Push state down: limit the scope of setState
What this chapter assumes
You know how to write a StatefulWidget, you have called setState many times, and you can run an app in debug mode. Earlier chapters covered why widgets rebuild and how to measure rebuilds. This chapter covers the first fix, which is to keep state as low in the tree as it can go.
What setState actually rebuilds
setState runs your closure, then calls markNeedsBuild on the State object's element. The framework adds that element to a dirty list. At the start of the next frame it calls build on every dirty element, and it does so once per frame even if you called setState several times.
The rebuild does not stop at that one build method. Your build creates new widget objects for its whole subtree. For each child slot, the framework compares the old and new widget:
- If the new widget is the same instance as the old one (
identical), it skips that child and everything under it. - If the types and keys match but the instance is different, it updates the existing element with the new widget, and that element's
buildruns again. - If the types or keys differ, it throws the old subtree away and builds a new one.
Case 2 is the costly one. A widget with the same type and the same field values still rebuilds when you create a new instance, because Widget equality is identity by default. Only a const instance, or one you stored and reused, takes case 1.
So the cost of a setState call is the size of the subtree under the State that calls it, minus the parts you manage to reuse. Moving state down shrinks that subtree.
The problem: state sits too high
Here is a screen that keeps a like counter in the same State that builds a large body. The classes ExpensiveHeader and ProductList print a line whenever they build, so you can see the cost.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ProfileScreen()));
class ExpensiveHeader extends StatelessWidget {
const ExpensiveHeader({super.key});
@override
Widget build(BuildContext context) {
debugPrint('ExpensiveHeader build');
return const Padding(
padding: EdgeInsets.all(16),
child: Text('Profile', style: TextStyle(fontSize: 24)),
);
}
}
class ProductList extends StatelessWidget {
const ProductList({super.key, required this.items});
final List<String> items;
@override
Widget build(BuildContext context) {
debugPrint('ProductList build');
return Column(children: [for (final item in items) Text(item)]);
}
}
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
final List<String> _items = List.generate(20, (i) => 'Product $i');
int _likes = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const ExpensiveHeader(),
Text('Likes: $_likes'),
ElevatedButton(
onPressed: () => setState(() => _likes++),
child: const Text('Like'),
),
ProductList(items: _items),
],
),
),
);
}
}Run this in debug mode and tap Like. The console prints ProductList build on every tap. The header stays quiet because it is const. ProductList cannot be const here, since it receives _items at runtime. Each tap therefore creates a new ProductList instance, and the framework rebuilds it even though nothing about it changed.
The fix: move state down
The like count affects only the text and the button. Give those two widgets their own State, and make the screen stateless.
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
static const List<String> _items = ['Product 0', 'Product 1', 'Product 2'];
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: Column(
children: [
ExpensiveHeader(),
LikeCounter(),
ProductList(items: _items),
],
),
),
);
}
}
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++),
),
],
);
}
}This reuses ExpensiveHeader and ProductList from the first listing. A tap now marks only _LikeCounterState dirty. Its build creates a Row, a Text and an IconButton, and nothing else runs. The console stays silent on every tap. Making the screen stateless also lets its whole body be const, so even the screen's own build rarely runs again.
Choose the lowest widget that needs the state
Place state in the lowest widget whose subtree contains every reader and every writer of that value. The table shows common cases.
| Situation | Where the state lives |
|---|---|
| Only one button and one label use the value | A small widget that contains both |
| Two siblings, such as a badge and a button, share the value | A small widget that wraps just those two siblings |
| A value is read across several screens | Not `setState`. Use an app-level `ChangeNotifier`, a `ValueNotifier` or another state tool (later chapters) |
| A `TextEditingController` drives a single field | The widget that owns that field |
For the sibling case, create a wrapper that is as small as possible:
class LikePanel extends StatefulWidget {
const LikePanel({super.key});
@override
State<LikePanel> createState() => _LikePanelState();
}
class _LikePanelState extends State<LikePanel> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Row(
children: [
Badge(label: Text('$_likes'), child: const Icon(Icons.favorite)),
ElevatedButton(
onPressed: () => setState(() => _likes++),
child: const Text('Like'),
),
],
);
}
}The panel rebuilds a badge and a button. It does not rebuild the screen around it.
When the state owner must wrap big content
Sometimes the widget that owns the state has to contain expensive content. A collapsible section is an example. The section needs an _expanded flag, and the body inside it is large. You can still avoid rebuilding the body by passing it in as a constructor argument.
class CountingFrame extends StatefulWidget {
const CountingFrame({super.key, required this.child});
final Widget child;
@override
State<CountingFrame> createState() => _CountingFrameState();
}
class _CountingFrameState extends State<CountingFrame> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Taps: $_taps'),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: const Text('Tap'),
),
widget.child,
],
);
}
}The parent creates the child once, for example CountingFrame(child: ProductList(items: items)). When _taps changes, build reads widget.child, which is the same instance as before. The framework sees case 1 from earlier and skips it. The parent must not rebuild for this to work, because a rebuilding parent creates a new child each time. The builder child parameter, covered in a later chapter, applies the same idea.
Edge cases and common mistakes
Callbacks that push state back up
A common regression is a small widget that reports changes to its parent through a callback, where the parent then calls setState. The child is small, but the state is high again.
// The parent rebuilds its whole body on every change.
LikeButton(onChanged: (value) => setState(() => _likes = value))Ask whether anything outside the child needs the value. If only the child displays it, keep it in the child. If something else needs it, find the smallest shared ancestor instead of the screen.
Listeners that call setState on scroll
A ScrollController listener that calls setState on a screen-level State rebuilds the whole screen on every scroll tick. If you only need to show a "back to top" button, put the listener in a small widget that owns that button.
Async work and the mounted check
State that is low in the tree is also more likely to be removed while work is in flight, so guard async setState calls.
Do the expensive work outside the closure and keep the closure itself small:
Future<void> _refresh() async {
final result = await fetchLikes(); // Any async call that returns an int.
if (!mounted) return;
setState(() => _likes = result);
}State that must survive
A widget that is moved lower in the tree, or that sits in a list whose order changes, can lose its State if its key or position changes. If you extract state into list items, give the items stable keys, as shown in a later chapter on lazy lists.
Over-splitting
Do not split every Text into its own stateful widget. Each extra class adds code, and a Text rebuild costs very little. Move state down when a setState call rebuilds a subtree that is large or costly. Use the measurements from the previous chapter, debugPrintRebuildDirtyWidgets and the DevTools rebuild counts, to decide.
Summary of the steps
- Find the
setStatecall that fires most often, such as a tap, a timer or a scroll listener. - List which widgets read the changed value.
- Extract those widgets and the value into the smallest widget class that holds them all.
- Make the original screen stateless where possible, and use
constfor everything that does not depend on the moved state. - Re-run the build log and confirm that only the small widget rebuilds.
Exercise
A checkout screen is a StatefulWidget. Its State holds a TextEditingController for a promo code field and a bool _applied flag that changes a small "Promo applied" label. The same build method also builds a long order summary from a list passed in by the constructor. Typing in the field does not call setState, but pressing Apply does. Where should the state go, and why does the order summary currently rebuild?
Show answer
Move the controller and _applied into a small PromoCodeSection widget that contains the field, the Apply button and the label. The screen can then be stateless. The summary rebuilds today because Apply calls setState on the screen's State, which re-runs the whole build method. The summary is created as a new, non-const instance each time, so the framework updates it and calls its build again.
Exercise
A parent calls setState and rebuilds, and its child CountingFrame receives widget.child as a constructor argument. Will the inner widget.child be skipped when CountingFrame calls its own setState? Will it be skipped when the parent calls setState?
Show answer
When CountingFrame calls its own setState, the inner child is skipped, because widget.child is the same instance as before. When the parent calls setState, the parent's build creates a new child instance, so the inner child is not identical and it rebuilds, unless the parent created it with const.