Sub topic 9
The State lifecycle
This chapter assumes you can write a StatefulWidget with a State class and call setState. It also assumes you know that widgets are immutable descriptions that Flutter rebuilds often. Here you will learn the order in which Flutter calls a State object's methods, what each method is for, and which mistakes this order causes.
Why a lifecycle exists
A StatefulWidget is thrown away and recreated whenever its parent rebuilds. The State object is different. Flutter creates it once, keeps it while the widget stays at the same place in the tree, and discards it when the widget leaves the tree.
That longer life means a State object can own resources. Examples are controllers, timers, stream subscriptions, and animation tickers. Those resources need to be created at a known moment and released at a known moment. The lifecycle methods mark those moments.
The sequence of calls
The framework drives the lifecycle. You override methods, but you never call them yourself, except setState.
In the order they run:
createStateruns when the widget is first inflated into an element. It only builds theStateobject, so keep it to a single constructor call.initStateruns once, when theStateis inserted into the tree.didChangeDependenciesruns right afterinitState, and again whenever an inherited widget that thisStatedepends on changes.buildruns after those calls, and again after every trigger in the next list.didUpdateWidgetruns when the parent rebuilds and supplies a new widget of the same type and key.deactivateruns when theStateis removed from the tree. It can be reinserted if the subtree moves.disposeruns when theStateis permanently removed. It is the last call.
Three events can trigger a rebuild after the first build: setState, a new widget from the parent (didUpdateWidget), and a change in an inherited dependency (didChangeDependencies).
What each method is for
| Method | Runs | Use it for | Avoid |
|---|---|---|---|
| `initState` | Once, at insertion | Creating controllers, starting subscriptions, reading `widget` fields | Using `BuildContext` to look up inherited widgets |
| `didChangeDependencies` | After `initState`, then on dependency change | Reading `Theme.of`, `MediaQuery.of`, `Localizations.of` | Heavy work that repeats on every change |
| `didUpdateWidget` | Each time the parent supplies a new widget | Comparing old and new configuration and reacting | Assuming it runs only when values differ |
| `build` | Many times | Returning a widget tree from current state | Side effects, network calls, creating controllers |
| `dispose` | Once, at removal | Releasing everything `initState` created | Calling `setState` |
initState and dispose in pairs
Treat initState and dispose as a matched pair. Whatever you create in the first, you release in the second.
import 'package:flutter/material.dart';
class SearchBox extends StatefulWidget {
const SearchBox({super.key, required this.onQuery});
final ValueChanged<String> onQuery;
@override
State<SearchBox> createState() => _SearchBoxState();
}
class _SearchBoxState extends State<SearchBox> {
late final TextEditingController _controller;
late final FocusNode _focusNode;
@override
void initState() {
super.initState();
_controller = TextEditingController();
_focusNode = FocusNode();
_controller.addListener(_handleChange);
}
void _handleChange() {
widget.onQuery(_controller.text);
}
@override
void dispose() {
_controller.removeListener(_handleChange);
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller, focusNode: _focusNode);
}
}Two ordering rules apply here:
- Call
super.initState()first ininitState. - Call
super.dispose()last indispose.
The superclass sets up and tears down framework bookkeeping. Your setup should come after the framework's, and your teardown should come before it.
Creating a controller inside build is a common bug. build can run many times per second, so every call would make a new controller. The old ones would leak, and the text field would lose its text.
Reacting to new configuration with didUpdateWidget
initState runs only once, but the parent can pass different values later. The State object survives, and widget now points to the new configuration. didUpdateWidget receives the previous widget as oldWidget, so you can compare the two.
This timer restarts when the parent changes its interval:
import 'dart:async';
import 'package:flutter/material.dart';
class Ticker extends StatefulWidget {
const Ticker({super.key, required this.interval});
final Duration interval;
@override
State<Ticker> createState() => _TickerState();
}
class _TickerState extends State<Ticker> {
Timer? _timer;
int _ticks = 0;
@override
void initState() {
super.initState();
_startTimer();
}
void _startTimer() {
_timer = Timer.periodic(widget.interval, (_) {
setState(() => _ticks++);
});
}
@override
void didUpdateWidget(Ticker oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.interval != widget.interval) {
_timer?.cancel();
_startTimer();
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text('Ticks: $_ticks');
}
}Without didUpdateWidget, the timer would keep the interval it read in initState. The Ticker would ignore the new value, even though widget.interval had changed.
The framework calls didUpdateWidget on every parent rebuild, even when the new widget has identical values. That is why the example compares oldWidget.interval with widget.interval before doing any work. You do not need to call setState inside didUpdateWidget. A build always follows it.
didChangeDependencies and BuildContext
An inherited widget is one that descendants read through BuildContext, such as Theme or MediaQuery. Calling Theme.of(context) registers the State as dependent. When the theme changes, Flutter calls didChangeDependencies and then build.
You cannot register a dependency inside initState. The element is not fully set up at that point, and Flutter throws an assertion error. Use didChangeDependencies or build instead.
import 'package:flutter/material.dart';
class ThemedLabel extends StatefulWidget {
const ThemedLabel({super.key});
@override
State<ThemedLabel> createState() => _ThemedLabelState();
}
class _ThemedLabelState extends State<ThemedLabel> {
late Color _accent;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_accent = Theme.of(context).colorScheme.primary;
}
@override
Widget build(BuildContext context) {
return Text('Accent label', style: TextStyle(color: _accent));
}
}In this small example you could read the theme directly in build. Prefer that when it works. Use didChangeDependencies when a dependency change must trigger work that does not belong in build, such as restarting a subscription.
Async work and the mounted check
A State can be disposed while an await is still pending. If the code then calls setState, Flutter throws an error, because the State is no longer in the tree. The mounted property is true between initState and dispose. Check it after every await that comes before a setState or a BuildContext use.
import 'package:flutter/material.dart';
Future<String> fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
class NameLoader extends StatefulWidget {
const NameLoader({super.key});
@override
State<NameLoader> createState() => _NameLoaderState();
}
class _NameLoaderState extends State<NameLoader> {
String? _name;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final result = await fetchName();
if (!mounted) return;
setState(() => _name = result);
}
@override
Widget build(BuildContext context) {
return Text(_name ?? 'Loading...');
}
}_load is called from initState without await. That is fine, because initState cannot be async and the method does not need to wait for the result. Never mark initState as async.
Deactivate, reinsertion, and hot reload
deactivate is rarely needed. The framework calls it when a State leaves the tree. If the subtree is moved to another place (for example, with a GlobalKey) in the same frame, the State is reinserted and dispose is never called. Most apps release resources in dispose and ignore deactivate.
During hot reload, Flutter calls reassemble and rebuilds, but it does not call initState again. If you change code in initState, the new code will not run for existing widgets. Use hot restart to see it.
Common lifecycle mistakes
- Missing dispose. Controllers,
FocusNodes,AnimationControllers,Timers, andStreamSubscriptions all need releasing. The result of forgetting is a memory leak or callbacks that fire after the widget is gone. - Calling
setStateafter dispose. Guard async code withmounted. - Side effects in
build. Starting a request inbuildrepeats it on every rebuild. - Reading
widgetfields only ininitState. Values copied there go stale when the parent passes new ones. Readwidget.xdirectly, or handle the change indidUpdateWidget. - Forgetting
supercalls. Always callsuper.initState(),super.didUpdateWidget(oldWidget),super.didChangeDependencies(), andsuper.dispose().
Exercise
A widget Clock is a StatefulWidget that takes a Duration tick parameter. Its State starts a Timer.periodic(widget.tick, ...) in initState. The parent changes tick from 1 second to 5 seconds, but the clock keeps ticking every second. Which lifecycle method should you override to fix this, and what should it do?
Show answer
Override didUpdateWidget(Clock oldWidget). Call super.didUpdateWidget(oldWidget), then if oldWidget.tick != widget.tick, cancel the existing timer and start a new one with widget.tick. Also cancel the timer in dispose.
Exercise
In which method can you not safely call Theme.of(context) for the first time, and where should you move that call?
Show answer
initState is the method where the lookup is not allowed, because inherited dependencies cannot be registered yet. Move it to didChangeDependencies or to build.