Sub topic 11
What setState really does
This chapter assumes you can write StatefulWidgets and know what the widget and element trees are. It follows one setState call from your code to the next frame. The call does not rebuild anything itself. It only records that something needs rebuilding.
The three steps inside setState
State.setState does three things:
- It asserts that the call is legal. The State must still be mounted, and the callback must not return a
Future. - It runs your callback immediately and synchronously.
- It calls
markNeedsBuild()on the State'sStatefulElement.
The callback only changes your fields. Rebuilding is a separate step that happens later. Here is the counter from earlier chapters.
import 'package:flutter/widgets.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _count++),
child: Text('Taps: $_count'),
);
}
}When the tap handler runs, _count is incremented at once. build has not run yet.
From markNeedsBuild to a scheduled frame
Element.markNeedsBuild is short:
- If the element is not active, it returns without doing anything.
- If the element is already marked dirty, it returns without doing anything.
- Otherwise it sets the element's dirty flag and calls
owner.scheduleBuildFor(this).
The owner is the BuildOwner, which keeps a list of dirty elements. When the first element is added to an empty list, the owner calls its onBuildScheduled callback. The binding responds by calling ensureVisualUpdate, which asks the engine for a frame. Later elements added to the list do not schedule another frame.
What happens during the frame
When the frame starts, the build phase runs BuildOwner.buildScope. It sorts the dirty elements by depth, so parents rebuild before children. It then calls rebuild() on each element that is still dirty.
For a StatefulElement, rebuild() calls State.build. The element then calls updateChild with the returned widget. This is the reconciliation step from the earlier chapter. It applies Widget.canUpdate, which compares runtime type and key. If they match, the child element is updated in place. If not, the old element is removed and a new one is created.
After the build phase, the frame continues with layout, paint, and compositing. Render objects only redo work if the updated elements marked them for layout or paint. For example, changing Text data tells its RenderParagraph to relayout. A parent that rebuilds with an identical configuration may cause no layout or paint work.
| Step | Where it happens | When it happens |
|---|---|---|
| Run the callback | `State.setState` | Immediately |
| Mark the element dirty | `Element.markNeedsBuild` | Immediately |
| Schedule a frame | `BuildOwner` and the scheduler | Immediately, once per frame |
| Call `build` | `BuildOwner.buildScope` | In the next frame |
| Layout and paint | Render objects | Later in the same frame, only if marked |
Consequences
Calls are batched
Calling setState three times in one event handler runs all three callbacks. The element is marked dirty once, and build runs once in the next frame. You do not need to merge them.
void _reset() {
setState(() => _count = 0);
setState(() => _label = 'Reset');
setState(() => _enabled = true);
// One build in the next frame, which sees all three changes.
}Changing a field without setState does nothing visible
If you change _count and never call setState, no element is marked dirty and no frame is scheduled. The field holds the new value, but the screen keeps showing the old one until something else triggers a rebuild of this widget.
Only the subtree below the State rebuilds
setState marks one element. That element's build runs, and the widgets it returns are reconciled against the existing children. Ancestors and siblings are not rebuilt. A child whose widget is the identical instance as before (for example a const widget) is skipped completely. A child with an equal-looking but new instance is updated, and a StatelessWidget child will run build again.
Calling setState at the wrong time
Do not call setState inside build. The element is already being rebuilt, and Flutter reports this as an error. After dispose, setState throws, because the element is no longer active. This usually happens after an await:
import 'package:flutter/widgets.dart';
class Loader extends StatefulWidget {
const Loader({super.key});
@override
State<Loader> createState() => _LoaderState();
}
class _LoaderState extends State<Loader> {
String _text = 'Loading';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
// Do the asynchronous work outside the setState callback.
final result = await Future<String>.delayed(
const Duration(seconds: 1),
() => 'Done',
);
// The widget may have been removed while we waited.
if (!mounted) return;
setState(() => _text = result);
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Text(_text),
);
}
}The callback passed to setState must be synchronous. An async callback returns a Future, which triggers an assertion in debug mode. Do the awaiting first, then assign the result inside the callback.
The callback is optional in effect
You can write _count++; setState(() {}); and get the same screen. The callback form is a convention. It keeps the state change and the rebuild request in one place, so you do not forget one of them.
Where to call setState
Call setState as low in the tree as practical. If only a counter label changes, put the State in a small widget around that label. Then the dirty element is small, and its build does little work. A State high in the tree rebuilds a large subtree on each call. Reconciliation stops early only for children whose widget instances are identical, such as const widgets.
Exercise
A State object's tap handler calls setState three times in a row, and each callback increments _count. How many times does build run, and what does _count equal when it runs?
Show answer
build runs once, in the next frame. Each callback runs immediately, so _count has increased by three when build runs. The first call marks the element dirty and the next two find it already dirty and return.
Exercise
A widget awaits a network call and then calls setState. Sometimes the user has left the screen by then and an error appears. What fixes it, and why does the error occur?
Show answer
Check mounted after the await and return early if it is false. The error occurs because the element was unmounted and the State disposed while the call was pending, and setState on a disposed State throws.