Sub topic 6
Writing a StatefulWidget and its State
This chapter covers how a StatefulWidget is split into two classes, why Flutter splits it that way, and how to write one correctly. It assumes you know basic Dart (classes, constructors, final fields, named parameters), null safety, and how to run a simple Flutter app. It also assumes you have already written a StatelessWidget and understand that build describes UI.
Why a second kind of widget exists
A StatelessWidget is a pure description. Given the same constructor arguments, it describes the same UI. That works until something on screen must change because of a tap, a timer, or a network response. A counter, a checkbox, and a text field with typed text all need to remember something between frames.
Widgets are immutable and are recreated often, so they cannot hold that memory. Any field you changed on a widget would vanish the next time the parent rebuilt and created a fresh instance. Flutter solves this by putting the changing data in a separate, long-lived object called the State.
The two-class structure
A stateful widget is written as two classes:
- The
StatefulWidgetsubclass. It is immutable and holds configuration passed in by its parent, asfinalfields. Its only required method iscreateState. - The
State<T>subclass. It holds the mutable data and has thebuildmethod.
Here is the smallest useful example.
import 'package:flutter/material.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: _increment,
child: Text('Count: $_count'),
);
}
}Three details are worth reading closely.
Counterhas no mutable fields. It can use aconstconstructor, like a stateless widget._CounterStateis private (leading underscore). Nothing outside the file needs to construct it.createStatereturns it through the publicState<Counter>type.buildlives on theState, not on the widget. Inside it you can read the current_countdirectly.
How the State survives rebuilds
The Counter widget object may be created many times. Each time a parent rebuilds, it runs const Counter() or Counter() again and produces a new widget instance. The State object is not recreated. Flutter's element tree holds the State, and when a new widget arrives at the same position with the same type and key, the element keeps its existing State and attaches the new widget to it.
This is why _count keeps its value when the parent rebuilds. It also explains how a State reads its configuration. The widget property always refers to the current widget instance attached to the State.
import 'package:flutter/material.dart';
class Titled extends StatefulWidget {
const Titled({super.key, required this.title});
final String title;
@override
State<Titled> createState() => _TitledState();
}
class _TitledState extends State<Titled> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _taps++),
child: Text('${widget.title}: $_taps'),
);
}
}Here title is configuration owned by the parent and read through widget.title. _taps is state owned by the State. If the parent passes a new title, the label changes but _taps stays.
Updating the UI with setState
Changing a field does not redraw anything. You must tell the framework that the state changed, and setState does that. It runs the callback you give it, then marks the element as dirty. The framework calls build again on the next frame.
The rules for setState:
- Put the mutation inside the callback. Changing a field outside it and calling
setState(() {})afterwards usually works, but putting the change inside keeps the intent clear. - The callback must be synchronous. It cannot be
async, and Flutter's debug mode asserts if it returns aFuture. - Do slow work first, then call
setStatewith only the assignment. - Do not call
setStatefrom insidebuild. That would schedule a build while building.
import 'package:flutter/material.dart';
class Loader extends StatefulWidget {
const Loader({super.key});
@override
State<Loader> createState() => _LoaderState();
}
class _LoaderState extends State<Loader> {
String _text = 'Not loaded';
Future<void> _load() async {
final result = await Future<String>.delayed(
const Duration(seconds: 1),
() => 'Loaded',
);
if (!mounted) return;
setState(() {
_text = result;
});
}
@override
Widget build(BuildContext context) {
return TextButton(onPressed: _load, child: Text(_text));
}
}The mounted check matters. If the user leaves the screen during the one-second delay, the State is disposed. Calling setState on a disposed State throws an error in debug builds. mounted is true while the State is in the tree.
Setup and cleanup: initState and dispose
Some objects must be created once and released later. Controllers, focus nodes, animation controllers, and stream subscriptions are typical. Create them in initState, which runs once when the State is inserted into the tree. Release them in dispose, which runs once when it is removed.
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
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
}Order matters with the super calls. In initState, call super.initState() first. In dispose, call super.dispose() last. This keeps your setup after the framework's setup and your cleanup before the framework's teardown.
The late final field is assigned in initState. You cannot use widget in a field initializer, because the State has no widget attached yet at construction time. initState is the first place it is safe.
Reacting to new configuration: didUpdateWidget
initState runs once, so it does not see later changes to the widget's fields. If the parent passes a different initialName to NameField after the first build, the controller still holds the old text. When your State derives something from configuration, override didUpdateWidget. The framework calls it after attaching the new widget, passing the previous one.
@override
void didUpdateWidget(covariant NameField oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialName != oldWidget.initialName) {
_controller.text = widget.initialName;
}
}Compare old and new values before acting. didUpdateWidget runs on every parent rebuild, even when nothing relevant changed.
The lifecycle at a glance
| Method | Runs | Typical use |
|---|---|---|
| `createState` | Once, on the widget | Return a new `State` |
| `initState` | Once, after the State is created | Create controllers, subscribe |
| `didChangeDependencies` | After `initState`, and when an inherited widget changes | Read `Theme.of(context)` or similar |
| `build` | Many times | Return the UI |
| `didUpdateWidget` | When the parent supplies a new widget | React to changed configuration |
| `dispose` | Once, at removal | Release resources |
The next chapters cover the lifecycle in more detail. For now, remember the pairing: whatever you create in initState, you release in dispose.
Common errors
- Mutable fields on the widget. Non-final fields on a
StatefulWidgettrigger an analyzer warning. Values that change belong in theState. - Using
widgetin a field initializer. Move that code toinitState. - Forgetting
dispose. Controllers and subscriptions leak, and listeners keep firing after the screen is gone. - Calling
setStateafter anawaitwithout checkingmounted. This throws when the user navigated away. - Expecting
initStateto rerun. It runs once. UsedidUpdateWidgetfor later changes. - Doing heavy work in
build.buildcan run on every frame during animation, so keep it fast and free of side effects.
Exercises
Exercise
A StatefulWidget declares int count = 0; as a field on the widget class and increments it inside setState. Why is this wrong, and where should the field go?
Show answer
A widget is immutable and is recreated whenever its parent rebuilds, so a field on it would be reset or lost, and the analyzer flags non-final fields. The field belongs in the State subclass, which survives rebuilds. The widget should hold only final configuration.
Exercise
A State creates an AnimationController in initState. Which method must release it, and in what order relative to super?
Show answer
dispose must call the controller's dispose method. Call super.dispose() last, after your own cleanup.
Exercise
Inside a State method you write await fetchName() and then call setState(() => _name = result). The user may leave the screen during the await. What check prevents an error?
Show answer
Check if (!mounted) return; after the await and before setState. mounted is false once the State has been disposed.