Sub topic 9
Where State lives and why it survives rebuilds
This chapter assumes you know how widgets compose, how StatefulWidget and State are declared, and that a widget is an immutable description (see the earlier chapters on widgets and elements). Here you will see where the State object is stored, when Flutter creates and discards it, and why build can run hundreds of times without resetting your fields.
The owner is the element
A StatefulWidget is a configuration object like any other. It is immutable and cheap, and Flutter may create a new one on every parent rebuild. It does not hold your mutable data.
The State object is held by the StatefulElement that the widget inflates into. The element does three things:
- When it is constructed, it calls
widget.createState()once and stores the result. - It links the state to itself, so
State.contextreturns the element andState.widgetreturns the element's current widget. - It forwards lifecycle events to the state: mount, update, deactivate, and unmount.
Because elements are long-lived, the State they own is long-lived too. A rebuild does not recreate the element. It gives the existing element a new widget, and the element hands that widget to the existing State.
The lifecycle of a State object
The State goes through a fixed sequence of calls, and each call has a specific purpose.
| Method | Runs | Use it for |
|---|---|---|
| `createState` | Once, when the element is created | Nothing except returning the object |
| `initState` | Once, before the first build | One-time setup: controllers, subscriptions |
| `didChangeDependencies` | After `initState`, and when an inherited dependency changes | Reading `InheritedWidget` data through `context` |
| `build` | Whenever the element rebuilds | Describing the UI from `widget` and fields |
| `didUpdateWidget` | When the parent supplies a new widget that passed `canUpdate` | Comparing `oldWidget` to `widget` and reacting |
| `deactivate` | When the element is removed from the tree | Rarely needed |
| `dispose` | Once, when the element is permanently gone | Cancelling timers and subscriptions, disposing controllers |
Always call super.initState() first and super.dispose() last in their overrides.
Watching it happen
This program prints each lifecycle call. Tap "rename" to change the label that the parent passes down. Tap the echo text to increment a counter that lives in the state.
import 'package:flutter/widgets.dart';
void main() => runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: Demo(),
),
);
class Demo extends StatefulWidget {
const Demo({super.key});
@override
State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
String _label = 'A';
@override
Widget build(BuildContext context) {
return Column(
children: [
GestureDetector(
onTap: () => setState(() => _label = _label == 'A' ? 'B' : 'A'),
child: const Text('rename'),
),
Echo(label: _label),
],
);
}
}
class Echo extends StatefulWidget {
const Echo({super.key, required this.label});
final String label;
@override
State<Echo> createState() => _EchoState();
}
class _EchoState extends State<Echo> {
int _taps = 0;
@override
void initState() {
super.initState();
debugPrint('initState (${widget.label})');
}
@override
void didUpdateWidget(Echo oldWidget) {
super.didUpdateWidget(oldWidget);
debugPrint('didUpdateWidget ${oldWidget.label} -> ${widget.label}');
}
@override
void dispose() {
debugPrint('dispose');
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _taps++),
child: Text('${widget.label}: $_taps'),
);
}
}Tap the echo text three times, then tap "rename". You will see didUpdateWidget A -> B and the text becomes B: 3. There is no second initState and no dispose. The widget changed from label A to label B, but canUpdate was true (same type, same key), so the element and its _taps field stayed.
Why `widget` is not a copy
State.widget is not fixed at creation. Each time the element updates, it assigns the new widget to the state before calling didUpdateWidget. This has two consequences.
- Read configuration through
widget.labelinbuild. Do not copy it into a field ininitStateunless you want a snapshot. A copied value goes stale when the parent passes a new one. - If a resource depends on configuration, rebuild it in
didUpdateWidget. For example, if a controller was created fromwidget.duration, compareoldWidget.durationwithwidget.durationand update the controller when they differ.
When State does not survive
State survives only as long as the element does. The element is kept when Widget.canUpdate returns true for the old and new widget at the same slot. It is thrown away, and its state disposed, in these cases:
| Change at the same position | Result |
|---|---|
| Same type, same key, new field values | Element and State kept; `didUpdateWidget` runs |
| Different `runtimeType` (for example `Echo` becomes `Padding(child: Echo)`) | Old element unmounted, `dispose` runs, new State created |
| Different key | Same as above |
| Siblings reordered, no keys | Elements matched by position, so State stays in its slot while widgets change |
| Siblings reordered, with keys | Elements matched by key, so State moves with its widget |
| Widget removed from the list | Element deactivated, then `dispose` runs at the end of the frame if nobody reinserts it |
Wrapping a stateful widget in a new parent is a common accidental reset. Adding Padding above Echo in one branch of an if changes the type at that slot. Everything below it is rebuilt from scratch.
Common errors
Keeping data in the widget. Widget fields are final, and a new widget replaces the old one on every rebuild. Mutable data belongs in the State.
Doing setup in build. build may run on every frame of an animation. Creating a controller or starting a request there repeats the work each time. Put one-time work in initState.
Calling setState after dispose. Once the element is unmounted, setState throws or logs an error. After any await, check mounted first:
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 {
await Future<void>.delayed(const Duration(seconds: 1));
if (!mounted) return;
setState(() => _text = 'done');
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Text(_text),
);
}
}Using context.dependOnInheritedWidgetOfExactType in initState. The element is not yet ready to register dependencies. Read inherited data in didChangeDependencies or build.
Forgetting to release resources. Anything you create in initState that holds a listener, timer, or stream needs a matching release in dispose.
Exercise
A screen shows Counter (a StatefulWidget with an int _count in its State). A parent rebuilds and now returns Padding(padding: EdgeInsets.all(8), child: Counter()) where it previously returned Counter() directly. What happens to _count, and which lifecycle methods run on the Counter's State?
Show answer
_count resets to 0. At that slot the widget type changed from Counter to Padding, so canUpdate is false. Flutter unmounts the old element, which calls dispose on the old State. It then creates a new Padding element and a new Counter element below it, which calls createState, initState, didChangeDependencies, and build on a fresh State.
Exercise
In the Echo example, you want Echo to restart a timer whenever its duration field changes, but not when label changes. Which lifecycle method do you use, and what do you compare?
Show answer
Use didUpdateWidget(Echo oldWidget). Compare oldWidget.duration with widget.duration. If they differ, cancel the old timer and start a new one. The state and element are the same across the update, so only this comparison tells you what changed.