Sub topic 9
Where State lives and why it survives rebuilds
Assume you know basic Dart classes and closures, and can compose StatelessWidget and StatefulWidget objects with widgets such as Row, Column, Padding, and Text.
A StatefulWidget is immutable configuration. Its State object stores mutable values that can change while the app runs. Flutter connects them through a StatefulElement.
| Object | Main role | Typical lifetime |
|---|---|---|
| `StatefulWidget` | Describes configuration | Recreated during rebuilds |
| `StatefulElement` | Connects configuration to state | Kept while the matching tree position remains |
| `State` | Stores mutable data and builds UI | Kept by its element |
The element owns the State
When Flutter first inserts a StatefulWidget, its element calls createState. The resulting State object belongs to that element. Flutter then calls the state's build method to create child widgets.
Calling setState does two things:
- It runs the callback that changes your data.
- It marks the associated
StatefulElementas needing a build.
During the next frame, Flutter calls build again. The State object is not recreated, so fields such as _count keep their values.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: CounterPage()));
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Persistent state')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: () => setState(() => _count++),
child: const Text('Add'),
),
],
),
),
);
}
}The CounterPage widget may be recreated when an ancestor rebuilds. That does not necessarily recreate _CounterPageState. Flutter compares the old and new widgets at the same location. If their runtime types and keys match, the existing element is updated with the new widget configuration, and its State remains attached.
When State is destroyed
Flutter removes the state when the matching element is removed, or when the new widget has a different runtime type or key. Before removal, Flutter calls dispose, where you should release resources such as controllers, timers, and subscriptions.
A key gives Flutter a stable identity when children move among siblings. For example, ValueKey('A') tells Flutter that the state for item A should follow item A rather than remain at its old list position.
Exercise
Why does a counter usually keep its value when its parent rebuilds?
Show answer
The matching StatefulElement is reused, so it keeps ownership of the same State object while Flutter calls build again.