Sub topic 2
How Flutter rebuilds UI from state
This chapter assumes you know Dart's async, await, and Future. It also assumes you can write a StatelessWidget and a StatefulWidget, and that you have used setState, initState, and dispose. Here you will learn what a rebuild is and when it happens. You will also learn which objects survive a rebuild and which are replaced. Every rule for FutureBuilder and StreamBuilder in later chapters follows from this model.
UI as a function of state
Flutter is declarative. You don't tell the screen to change. You describe what the screen should look like for the current state, and Flutter makes the screen match.
UI = build(state)The build method is that function. It takes the current state, plus inherited data from BuildContext, and returns a tree of widgets. When state changes, Flutter calls build again and compares the new description with the previous one. It updates only the parts of the screen that differ.
For async data this means you don't write "show a spinner, then hide it, then show text". You write one build that handles every possible state, and Flutter calls it again as the state moves from one to the next.
Three trees, three lifetimes
Three kinds of objects take part in a rebuild, and they live for different lengths of time.
| Object | Role | Lifetime |
|---|---|---|
| Widget | An immutable configuration: "a Text with this string" | Very short. A new one is usually created on every build. |
| Element | The live node in the tree that holds a widget and its place on screen | Long. It is reused while the widget at that position keeps the same type and key. |
| State | The mutable object behind a `StatefulWidget` | As long as its element. It is created once and disposed once. |
A third tree, the render objects, does layout and painting. You rarely touch it directly.
The most important consequence is that widgets are cheap and disposable. Creating hundreds of them per frame is normal. State objects are not disposable. They carry your data, your controllers, and your Future across rebuilds.
When an element is reused
When a parent rebuilds, Flutter walks the old and new children at each position and asks whether the old element can be updated with the new widget. The answer is yes when both widgets have the same runtimeType and the same key. In that case:
- The element stays.
- For a
StatefulWidget, the existingStatestays. Itswidgetfield now points to the new widget. - Flutter calls
didUpdateWidget(oldWidget)on theState, thenbuild.
If the type or key differs, Flutter discards the old element and its State. It calls dispose on the old state and creates a fresh element with a new State, which runs initState.
What triggers a rebuild
A widget's build can run for several reasons. Only the first is under your direct control.
| Trigger | What happens |
|---|---|
| `setState` in the widget's own `State` | That element is marked dirty and rebuilt on the next frame. |
| A parent rebuilds | The parent creates a new child widget, so the child's `build` runs again (unless the child is a `const` instance). |
| An `InheritedWidget` the widget depends on changes | Dependents are marked dirty. `Theme.of(context)`, `MediaQuery.of(context)`, and `Directionality` all work this way. |
| A listenable-based builder fires | `FutureBuilder`, `StreamBuilder`, `ValueListenableBuilder`, and `AnimatedBuilder` call `setState` internally when their source emits. |
| The route or window changes | Examples are a keyboard opening, a rotation, or a hot reload. |
Several of these can happen in the same frame. Flutter batches them: each dirty element is rebuilt at most once per frame, however many setState calls it received.
The rebuild cycle
Note that setState doesn't call build directly. It changes your fields, marks the element dirty, and returns. build runs later, when the frame starts. This is why you must not read the rebuilt UI on the line after setState.
A runnable demonstration
The following app shows the three lifetimes at once. The parent holds a tap counter. The child is a StatefulWidget that records when its State was created and how many times build has run.
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: Parent())),
),
);
}
class Parent extends StatefulWidget {
const Parent({super.key});
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Child(label: 'Taps: $_taps'),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: const Text('Tap'),
),
],
);
}
}
class Child extends StatefulWidget {
const Child({super.key, required this.label});
final String label;
@override
State<Child> createState() => _ChildState();
}
class _ChildState extends State<Child> {
late final int _createdAt;
int _builds = 0;
@override
void initState() {
super.initState();
_createdAt = DateTime.now().millisecondsSinceEpoch;
debugPrint('Child initState');
}
@override
void didUpdateWidget(Child oldWidget) {
super.didUpdateWidget(oldWidget);
debugPrint('Child didUpdateWidget: ${oldWidget.label} -> ${widget.label}');
}
@override
Widget build(BuildContext context) {
_builds++; // For demonstration only. Do not mutate fields in build.
return Text('${widget.label} | builds: $_builds | created: $_createdAt');
}
}Run it and tap the button three times. You will observe the following:
Child initStateprints once.Child didUpdateWidgetprints on every tap, because the parent made a newChildwidget with a different label.buildsincreases with each tap, whilecreatednever changes.
The Child widget object was replaced three times, but the _ChildState object was never replaced. That is the whole mechanism. Anything you store in State survives. Anything you create inside build is recreated each time.
The effect of `const`
If the parent wrote const Child(label: 'fixed'), Flutter would reuse the identical widget instance. It can skip rebuilding that subtree when the parent rebuilds. A const widget has no changing inputs, so there is nothing to recompute.
Rules for writing build
Because build can run on any frame, treat it as a pure description of the UI.
- Make it fast. It can run up to 60 or 120 times per second during animations.
- Make it free of side effects. Don't start network requests, open streams, show dialogs, or navigate from inside
build. - Make it repeatable. Calling it twice with the same state and inputs must produce the same widgets.
- Don't assume it runs once, or that it runs at all. Flutter may skip it for offscreen subtrees or call it extra times.
Where each kind of work belongs:
| Work | Where to put it |
|---|---|
| Starting a request or opening a stream | `initState`, or an event handler such as a button's `onPressed` |
| Reacting to a changed constructor argument | `didUpdateWidget` |
| Releasing controllers, subscriptions, timers | `dispose` |
| Deciding what to show for the current data | `build` |
| Values that must survive rebuilds (a `Future`, a `StreamController`) | Fields on the `State` |
Why this matters for async data
Think about what a FutureBuilder needs to do. It must take a Future and show a different widget at each stage. It is itself a StatefulWidget. Its State subscribes to the Future and stores the latest result. When the Future completes, it calls setState, and the framework rebuilds it through the cycle above.
That design only works if the Future handed to it stays the same between rebuilds. Here is how the rules from this chapter combine:
- Your parent's
buildruns many times, for example when the keyboard opens or a theme changes. - Each run creates a new
FutureBuilderwidget. The old element and itsStateare reused, because the type and key match. - The
FutureBuilder'sdidUpdateWidgetcompares the old and newfutureobjects. If they are different objects, it unsubscribes from the old one and subscribes to the new one. - A new
Futuretherefore means new loading state and often a new network call.
If your State stores the Future in a field, step 3 sees the same object and nothing restarts. If you create the Future inside build, step 3 sees a new object every time. StreamBuilder follows the same pattern with its stream argument.
Inspecting rebuilds in practice
When you suspect an unwanted rebuild, you have several tools.
- Add a
debugPrintat the top ofbuild. This is crude but quick, and it shows how often the method runs. - In Flutter DevTools, enable "Track widget rebuilds" in the Flutter Inspector. Rebuilt widgets are highlighted, and the Performance view shows build times.
- Set
debugPrintRebuildDirtyWidgets = true(frompackage:flutter/widgets.dart) in a debug build to log every widget that Flutter marks dirty.
A rebuild is not a bug in itself. Flutter is designed for frequent, cheap rebuilds. It becomes a problem when build does expensive work, or when it starts work with side effects, such as a network call.
Narrowing the rebuild scope
When only a small part of the screen depends on changing data, put that part in its own widget. Calling setState high in the tree rebuilds everything below it. Calling it in a small leaf widget rebuilds only that leaf. The builder widgets in this tutorial apply this idea. Each rebuilds only its own builder output when new data arrives, not the whole screen.
Common mistakes
- Mutating state without
setState. The fields change but no rebuild is scheduled, so the screen stays stale. Wrap the change insetState. - Calling
setStateafterdispose. An async callback can finish after the widget has left the tree. Flutter throws an error in debug mode. Checkmountedbefore callingsetStatein such callbacks. - Calling
setStateduringbuild. This asks for a rebuild while one is in progress and raises an assertion error. - Storing long-lived objects in local variables of
build. They are lost on the next call. Move them toStatefields. - Assuming a new widget means a new State. The
Statesurvives as long as type and key match at that position.
Exercise
A screen's build method contains FutureBuilder<String>(future: loadName(), builder: ...). The user rotates the phone, and the app makes a second network call and briefly shows the spinner again. Using the rebuild model from this chapter, explain why. Then say where the Future should be created, and in which method.
Show answer
Rotating the phone changes MediaQuery, which marks dependent widgets dirty, so build runs again. Each run calls loadName() and produces a new Future object. The FutureBuilder element and its State are reused, but in didUpdateWidget the builder sees that the new future is a different object from the old one. It unsubscribes from the old one and subscribes to the new one, which resets the snapshot to the waiting state and starts another request. The fix is to store the Future in a field of the State, created in initState (for example _name = loadName();), and pass future: _name to the FutureBuilder. Then every rebuild passes the same object and nothing restarts.
Exercise
In the demonstration app, you change Child(label: 'Taps: $_taps') to Child(key: ValueKey(_taps), label: 'Taps: $_taps'). What changes in the console output and in the displayed created value after each tap? Why?
Show answer
The key now differs on every tap, so the old and new Child widgets can't update the same element. Flutter disposes the old _ChildState and builds a new one. The console prints Child initState after every tap and no longer prints didUpdateWidget. The created value changes each time, and builds resets to 1, because each tap produces a fresh State object.