Sub topic 2
Where State Lives and When It Is Kept or Discarded
This chapter assumes basic Dart syntax, StatelessWidget and StatefulWidget, setState, Column, ListView, and ListTile.
Flutter rebuilds widget descriptions often. Rebuilding does not normally mean that all visible controls lose their state. Flutter separates the description of a widget from the object that keeps its position and state in the tree.
The three trees
A Widget is an immutable configuration. It describes what should appear, such as a CounterTile with the label "A". Flutter can create a new widget object on every rebuild.
An Element is a persistent object that connects a widget to its place in the tree. It stores relationships with the parent and children. Flutter compares a new widget with the widget already associated with an element.
A State object stores mutable data for a StatefulWidget. For example, _CounterTileState stores the counter value. The state belongs to the element, not to a particular widget object.
When setState runs, Flutter marks the element as needing a rebuild. Flutter calls build again with the same State object, unless the element has been removed or no longer matches.
The State lifecycle
A typical state object follows this sequence:
- Flutter creates the
Stateobject. - Flutter calls
initStateonce. - Flutter calls
buildone or more times. - Flutter may call
deactivatewhen the element is temporarily removed. - Flutter may call
activateif that element is inserted again. - Flutter calls
disposewhen the element will not return.
Use initState for one-time setup, such as creating a controller or starting a subscription. Use dispose to release those resources.
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
void initState() {
super.initState();
debugPrint('created ${widget.label}');
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
@override
void dispose() {
debugPrint('discarded ${widget.label}');
super.dispose();
}
}Changing widget.label does not automatically create a new State. Flutter updates the widget property on the existing state after matching the new widget to the element. If a value used by the state changes, compare the old and new values in didUpdateWidget.
When state is discarded
Flutter discards state when its element is removed permanently. Examples include:
- Removing the item from a list.
- Replacing a
StatefulWidgetwith a widget that does not match it. - Removing an entire route or subtree.
- Giving a list item a different identity so Flutter cannot match it to the previous element.
A rebuild alone does not discard state. Rebuilding a Column with new widget objects can reuse the existing elements when the widgets occupy matching positions.
This distinction causes a common bug. Suppose three counter tiles appear in the order A, B, C. If the list changes to C, B, A without keys, Flutter may reuse the first element for the new first position. The counter that belonged to A can now display beside C. The state was preserved, but it was preserved by position rather than by the logical item.
Keys provide an identity that Flutter can use when matching siblings. They are especially important when stateful children are inserted, removed, or reordered. The next step is to understand the exact matching rule and how keys change it.
Exercise
A parent rebuilds and creates a new CounterTile(label: 'A') object in the same position as before. Does Flutter necessarily create a new State object?
Show answer
No. If the new widget matches the existing element, Flutter reuses that element and its State object. The State is discarded only when the element is removed or no longer matches.