Sub topic 2
Where State lives and when it is kept or discarded
This chapter assumes you can build screens with StatelessWidget and StatefulWidget, call setState, and use Column, ListView and ListTile. It also assumes you know that Flutter builds a tree of widgets. The goal here is to show where a State object actually lives, what decides whether it survives a rebuild, and which events destroy it.
Widgets are cheap, State is not
A widget is an immutable description of part of the UI. Flutter creates new widget objects on every build, so a widget's fields never hold data that must survive between frames.
A State object is different. It is created once and kept for as long as the framework considers the widget to be "the same one". Your _count field in a State class survives rebuilds because the State object survives, not because the widget does.
A StatefulWidget itself holds only configuration, such as a label passed by the parent. It also has one method, createState, which makes the State object.
import 'package:flutter/material.dart';
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}In this class, label lives on the widget and can change from one frame to the next. _count lives on the State and persists. The State reads the current widget through widget.label, which always points to the newest configuration.
The Element owns the State
Between the widget and the State sits a third object, the Element. An Element is the live node in the element tree. It represents one widget instance at one position in the UI.
For a StatefulWidget, the Element is a StatefulElement. It does three jobs:
- It calls
createStateand holds the resultingStateobject. - It holds a reference to the current widget, which changes on rebuild.
- It holds the
State's link to the tree, which is theBuildContextyou receive inbuild. TheBuildContextis the Element.
So the ownership chain is: the Element owns the State, and the State points back to the Element through context. The widget is only a configuration that the Element is currently using.
| Object | Lifetime | Holds |
|---|---|---|
| Widget | One build. Recreated often. | Immutable configuration |
| Element | Long. Reused across builds. | Position in tree, current widget, the State |
| State | Same as its Element | Your mutable data and lifecycle methods |
This is why the question "is my state kept?" is really the question "is the Element kept?". If the Element is reused, its State is reused. If the Element is thrown away, the State goes with it.
What happens on a rebuild
When a parent calls setState or its inputs change, it builds a new list of child widgets. Flutter then walks the old Element and the new widget at each position and decides whether to update the Element or replace it. The next chapter covers that decision rule in detail. For now, this is the outcome you need:
- Kept: The Element stays. Flutter gives it the new widget and calls
didUpdateWidgeton theState, thenbuild. TheStateand its fields are unchanged. - Discarded: The old Element is removed, its
Stateis disposed, and a new Element and a newStateare created for the new widget. All fields start from their initial values.
The State lifecycle
The State object moves through a fixed sequence of calls. Knowing them tells you exactly where to put setup and cleanup code.
import 'package:flutter/material.dart';
class LifecycleDemo extends StatefulWidget {
const LifecycleDemo({super.key, required this.title});
final String title;
@override
State<LifecycleDemo> createState() {
debugPrint('createState');
return _LifecycleDemoState();
}
}
class _LifecycleDemoState extends State<LifecycleDemo> {
int _count = 0;
@override
void initState() {
super.initState();
debugPrint('initState');
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
debugPrint('didChangeDependencies');
}
@override
void didUpdateWidget(covariant LifecycleDemo oldWidget) {
super.didUpdateWidget(oldWidget);
debugPrint('didUpdateWidget: ${oldWidget.title} -> ${widget.title}');
}
@override
void dispose() {
debugPrint('dispose');
super.dispose();
}
@override
Widget build(BuildContext context) {
debugPrint('build');
return TextButton(
onPressed: () => setState(() => _count++),
child: Text('${widget.title}: $_count'),
);
}
}The methods run in this order:
| Method | When it runs | Typical use |
|---|---|---|
| `createState` | Once, when the Element is created | Return the `State` object |
| `initState` | Once, before the first build | Create controllers, subscribe to streams |
| `didChangeDependencies` | After `initState`, and when an inherited widget you read changes | React to `Theme`, `MediaQuery` and similar |
| `build` | Whenever the UI must be drawn | Return widgets, no side effects |
| `didUpdateWidget` | When the Element receives a new widget of the same type | Compare `oldWidget` with `widget`, update controllers |
| `dispose` | Once, when the Element is permanently removed | Cancel subscriptions, dispose controllers |
initState runs once per State. If a rebuild keeps the Element, initState does not run again, and a value computed there goes stale when the parent passes new input. That is the reason didUpdateWidget exists.
class _LifecycleDemoState extends State<LifecycleDemo> {
late String _shout = widget.title.toUpperCase();
@override
void didUpdateWidget(covariant LifecycleDemo oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.title != widget.title) {
_shout = widget.title.toUpperCase();
}
}
@override
Widget build(BuildContext context) => Text(_shout);
}If you compute _shout only in initState and the parent later changes title, the screen would keep showing the old text. The State is kept, so only didUpdateWidget can tell you that the input changed.
When State is discarded
A State is disposed when its Element leaves the tree for good. The common cases are:
- The widget stops being built. A parent uses
if (show) CounterTile(...)andshowbecomes false. The Element is removed,disposeruns, and the count is lost. Showing the tile again creates a newStatethat starts at zero. - The widget type at that position changes. A parent swaps a
CounterTilefor aTextat the same position. The old Element cannot be reused for a different kind of widget. - An ancestor is removed. Everything below it goes with it. Popping a route disposes all the
Stateobjects on that screen. - A lazy container drops off-screen children. A
ListView.builderonly builds items near the viewport. When an item scrolls far enough away, its Element is removed and itsStateis disposed. - A lazy tab container drops a page. A
TabBarViewbuilds only the page it needs, and may dispose pages the user has left.
State is kept when the same kind of widget is built again at the same place. A parent that rebuilds with setState does not by itself reset the children's state. A new widget object is not a new State.
Seeing it happen
The next widget shows both outcomes. Tap the counter a few times, then toggle the visibility switch.
import 'package:flutter/material.dart';
class ToggleDemo extends StatefulWidget {
const ToggleDemo({super.key});
@override
State<ToggleDemo> createState() => _ToggleDemoState();
}
class _ToggleDemoState extends State<ToggleDemo> {
bool _show = true;
int _rebuilds = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
if (_show) const CounterTile(label: 'Counter'),
TextButton(
onPressed: () => setState(() => _show = !_show),
child: Text(_show ? 'Hide' : 'Show'),
),
TextButton(
onPressed: () => setState(() => _rebuilds++),
child: Text('Rebuild parent ($_rebuilds)'),
),
],
);
}
}Place it under a Scaffold body so that ListTile has a Material ancestor. You will see this behavior:
- Tap the tile to raise the count to 3.
- Press Rebuild parent. The count stays at 3. The parent built a new
CounterTilewidget, but the Element andStatewere reused. - Press Hide, then Show. The count returns to 0. The Element was removed and a new one was created with a fresh
State.
The const constructor does not change this result. A const widget can be the same object across builds, but the State lives on the Element, not on the widget, so the rules above apply whether or not the widget is const.
A common source of confusion
Developers often say "Flutter rebuilt my widget, so I lost my state". That is almost never what happens. A rebuild alone does not reset a State. State is lost when the Element is removed or replaced. When you see state vanish, ask these questions in order:
- Was the widget removed from the tree, even briefly, by a condition such as
ifor a ternary expression? - Did the widget at that position change to a different type?
- Is the widget inside a lazy list or tab view that disposes off-screen children?
- Did an ancestor get replaced, for example by navigating to a new route?
The reverse problem also exists. Sometimes state is kept when you expected it to reset or move. That happens when the Element is reused for a widget of the same type at the same position, even though you meant it to be a different item. The next chapters build on exactly this behavior.
Summary of the model
- Widgets are immutable and rebuilt often. They carry configuration only.
- Each
StatefulWidgetgets an Element, and the Element owns theState. - If the Element is reused, the
Stateis reused, anddidUpdateWidgetreports the new configuration. - If the Element is removed, the
Stateis disposed and a later widget gets a new one. - Put one-time setup in
initState, input-dependent updates indidUpdateWidget, and cleanup indispose.
Exercise
A StatefulWidget called PriceTag takes a price parameter. In its State, initState copies the price into a field _formatted = format(widget.price). The parent rebuilds and passes a new price, but the screen still shows the old formatted value. Why does this happen, and what is the fix?
Show answer
The parent's rebuild created a new PriceTag widget, but the Element was reused, so the same State object stays and initState does not run again. _formatted was computed once from the old price. The fix is to override didUpdateWidget, compare oldWidget.price with widget.price, and recompute _formatted when they differ. Alternatively, compute the formatted value inside build so it always uses the current widget.price.
Exercise
In a screen, if (loggedIn) CounterTile(label: 'A') appears in a Column. The user taps the tile to raise the count, the loggedIn flag flips to false and then back to true. What is the count afterwards, and why?
Show answer
The count is 0. When the flag is false the widget is not built, so its Element is removed and its State is disposed. When the flag becomes true again, a new Element and a new State are created, and _count starts from its initial value.