Flutter StatefulWidget & setState
Some widgets need to remember things: how many times a button was tapped, whether a switch is on, which tab is selected. That changing data is called state, and widgets that own it extend StatefulWidget.
Two classes working together
A stateful widget is split into two classes:
- The widget class (extends
StatefulWidget) — immutable, holds configuration passed by the parent, and creates the state. - The state class (extends
State<MyWidget>) — long-lived, holds mutable fields and thebuild()method.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: LikeButton()))));
class LikeButton extends StatefulWidget {
const LikeButton({super.key});
@override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton> {
bool _liked = false;
int _count = 41;
void _toggle() {
setState(() {
_liked = !_liked;
_count += _liked ? 1 : -1;
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: _toggle,
icon: Icon(_liked ? Icons.favorite : Icons.favorite_border),
color: Colors.red,
),
Text('$_count likes'),
],
);
}
}The state class name starts with _, which makes it private to the file — nobody else should create it directly.
How setState works
setState() takes a callback. Inside it you change your fields; afterwards Flutter marks the widget as "dirty" and calls build() again on the next frame. The new widget tree is compared with the old one and only the changed parts are repainted.
Warning: Changing a field without
setState()updates the variable but not the screen — the UI stays stale until something else triggers a rebuild.
// ❌ The number changes in memory but the screen never updates
void _increment() {
_count++;
}
// ✅ Flutter is told to rebuild
void _increment() {
setState(() => _count++);
}A counter with debug output
debugPrint writes to the console in debug mode, which helps you watch the rebuild cycle:
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) {
debugPrint('build() with count = $_count');
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text('$_count', style: const TextStyle(fontSize: 64)),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}build() with count = 0
build() with count = 1
build() with count = 2
build() with count = 3
The console shows one build when the screen first appears and one per tap.
Accessing the widget's configuration
Values passed into the StatefulWidget are read from the state class through the widget property:
class Countdown extends StatefulWidget {
const Countdown({super.key, required this.start});
final int start;
@override
State<Countdown> createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
late int _remaining;
@override
void initState() {
super.initState();
_remaining = widget.start; // read configuration once
}
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: _remaining == 0 ? null : () => setState(() => _remaining--),
child: Text(_remaining == 0 ? 'Lift off!' : 'T-minus $_remaining'),
);
}
}Passing null as onPressed disables the button — a common Flutter idiom.
The State lifecycle
| Method | When it runs | Typical use |
|---|---|---|
initState() |
Once, when the state is created | Initialise fields, start controllers or listeners |
didChangeDependencies() |
After initState and when inherited data changes |
React to theme/locale changes |
build() |
Every time the widget must be drawn | Return the UI |
didUpdateWidget(old) |
Parent rebuilt with new configuration | Compare old and widget |
dispose() |
When the state is removed for good | Dispose controllers, cancel subscriptions |
Always call super.initState() first and super.dispose() last.
Tip: Keep state as low in the tree as possible. If only a button needs to know it is pressed, make the button stateful — not the whole screen.
Test yourself
What happens if you change a state field without calling setState()?
- The app crashes
- The field changes but the UI is not rebuilt
- Flutter automatically rebuilds
- The change is ignored
Inside a State class, how do you read a parameter passed to the StatefulWidget?
- this.param
- widget.param
- context.param
- state.param
Which lifecycle method should release controllers and cancel subscriptions?
- initState()
- build()
- dispose()
- didUpdateWidget()