Sub topic 9
The State lifecycle
Assume you know basic Dart classes, constructors, final fields, named parameters, and null safety. You also need a Flutter project that runs.
A StatefulWidget has two parts:
- The widget object holds immutable configuration.
- The
Stateobject holds data that can change while the widget is on screen.
Flutter creates, updates, and removes the State object through a lifecycle. Lifecycle methods are methods that Flutter calls at specific points in that process.
The lifecycle at a glance
The most commonly used lifecycle methods are:
| Method | When Flutter calls it | Typical use |
|---|---|---|
| `initState` | Once, after the `State` is inserted | Create controllers, subscriptions, or initial data |
| `didUpdateWidget` | When the parent supplies a new widget configuration | Respond to changed widget properties |
| `dispose` | Once, when the `State` is permanently removed | Release controllers, subscriptions, and listeners |
Flutter calls build many times. It calls initState and dispose only once for a particular State object.
`initState`: prepare once
Use initState for setup that should happen once. Always call super.initState() first.
The widget property gives the State object access to the StatefulWidget configuration. In this example, initialName is read when the controller is created.
import 'package:flutter/material.dart';
class NameField extends StatefulWidget {
const NameField({super.key, required this.initialName});
final String initialName;
@override
State<NameField> createState() => _NameFieldState();
}
class _NameFieldState extends State<NameField> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.initialName);
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}late final means the controller will be assigned later, exactly once. Creating it in build would create a new controller during rebuilds and could lose the user's text.
`didUpdateWidget`: react to new configuration
A parent can rebuild and pass new values to the same location in the tree. Flutter may keep the existing State object, then replace its widget property with the new widget. Flutter calls didUpdateWidget with the previous widget as oldWidget.
Use this method when a changing property requires you to update a subscription, controller, or other resource. Call super.didUpdateWidget(oldWidget) first.
@override
void didUpdateWidget(covariant NameField oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.initialName != widget.initialName &&
_controller.text != widget.initialName) {
_controller.text = widget.initialName;
}
}Do not copy every widget property into state automatically. Decide whether the property is configuration or editable local data. A text field may accept an initial value once, or it may deliberately synchronize with a parent value.
`dispose`: release resources
dispose runs when the State will never build again. Release anything that has a dispose, cancel, or remove-listener operation. Call super.dispose() last.
Common resources include:
TextEditingControllerAnimationControllerStreamSubscriptionFocusNode- Timers and listeners
After dispose, do not call setState. An asynchronous callback can finish after the widget has been removed, so check mounted before updating UI from such a callback.
A practical sequence
When debugging lifecycle behavior, ask:
- Was the
Statecreated? Put one-time setup ininitState. - Did the parent change the widget's properties? Compare
oldWidgetandwidgetindidUpdateWidget. - Is the resource still active? Clean it up in
dispose. - Could an asynchronous operation finish after removal? Check
mountedbefore callingsetState.
Exercise
Where should a TextEditingController be created and released, and why?
Show answer
Create it in initState and release it in dispose. This keeps one controller across rebuilds and prevents the controller from retaining resources after the State is removed.