Sub topic 10
Adding interaction with StatefulWidget and setState
This chapter assumes you can run a Flutter project with flutter run, and that you know what a widget is and how StatelessWidget and build() work. It also assumes you are comfortable with Dart classes, closures, and generics at a basic level.
By the end you will be able to explain why Flutter splits interactive widgets into two classes. You will also be able to write a counter with setState, and you will be able to recognize the errors people hit most often when they start using it.
Why a second kind of widget exists
A StatelessWidget is immutable. Its fields are final, and once Flutter creates it, nothing about it changes. If the screen has to change, a parent builds a new widget with new values and hands it down.
Many screens need data that changes while the user interacts with them: a counter, a checked box, text typed into a field, a selected tab. That data is called state. State is data that can change during the lifetime of a widget and that affects what the widget draws.
Flutter puts that data in a separate object, so it survives while widgets are rebuilt. Widgets are cheap, short-lived descriptions of the UI, and Flutter may recreate them many times per second. If you stored a counter in a field of the widget itself, it would reset every time the parent rebuilt.
The two-class pattern
An interactive widget is written as two classes:
- A class that extends
StatefulWidget. It is immutable, like any widget. It holds configuration passed in by the parent. - A class that extends
State<YourWidget>. It holds the mutable data and implementsbuild().
The pairing happens in createState(), a method on the widget that returns a new State object.
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}The State class is usually private (the leading underscore) because nothing outside the file needs it.
class _CounterPageState extends State<CounterPage> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
// returns the UI, reading _count
return const SizedBox();
}
}Two details matter here. First, _count lives in the State object, not in the widget. Second, build() is on the State, so it can read _count directly. If it needs the widget's own configuration, it reads it through the widget property, for example widget.title.
The complete counter app
This is the full lib/main.dart. A stateless root configures the app, and a stateful page owns the counter.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'First App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const CounterPage(),
);
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text(
'Taps: $_count',
style: Theme.of(context).textTheme.headlineMedium,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}Replace the contents of lib/main.dart with this code and run flutter run. Each tap on the button raises the number on screen by one.
What setState actually does
setState takes a function, runs it right away, and then marks the State object as dirty. A dirty element is scheduled for a rebuild. On the next frame, Flutter calls build() again on that State, and the new widgets it returns are compared with the old ones. Only the parts of the render tree that actually changed are updated on screen.
So setState does not draw anything itself. It records that your data changed and asks for a new build().
diagram mermaid
caption: What happens when the user taps the button
alt: Sequence from a tap on the button through the onPressed handler and setState to a new build call and an updated screen.
sequenceDiagram
participant U as User
participant B as FloatingActionButton
participant S as State object
participant F as Flutter framework
U->>B: tap
B->>S: onPressed calls _increment()
S->>S: setState runs the callback, _count becomes 1
S->>F: mark State as dirty
F->>S: next frame: call build()
S-->>F: new widget tree showing "Taps: 1"
F-->>U: updated screenState lifecycle
A State object has a lifecycle with methods you can override. Three come up constantly.
| Method | When it runs | Typical use |
|---|---|---|
| `initState()` | Once, when the `State` is created and inserted into the tree | Set up controllers, subscribe to streams |
| `build()` | On first display and after every `setState` or parent change | Return the UI |
| `dispose()` | Once, when the `State` is removed for good | Cancel subscriptions, dispose controllers |
If you override initState(), call super.initState() first. If you override dispose(), call super.dispose() last.
class _TimerPageState extends State<TimerPage> {
late final Timer _timer;
int _seconds = 0;
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
setState(() => _seconds++);
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(child: Text('Seconds: $_seconds'));
}
}This sketch needs import 'dart:async'; and a matching TimerPage class that extends StatefulWidget. It shows why dispose() matters. Without _timer.cancel(), the timer would keep firing after the page is gone.
Common errors and gotchas
Changing state without setState
If you write _count++ outside of setState, the variable changes but nothing tells Flutter to rebuild. The screen stays stale until something else triggers a rebuild, which makes the bug look random.
void _incrementBroken() {
_count++; // value changes, screen does not
}Put the mutation inside the callback, or mutate first and then call setState(() {}). The first form is the convention because it keeps the change and the rebuild request together.
Calling setState after dispose
If an asynchronous task finishes after the user has left the screen, calling setState throws an error saying it was called after dispose(). Check the mounted property first.
Future<void> _load() async {
await Future<void>.delayed(const Duration(seconds: 2));
if (!mounted) return;
setState(() {
_count = 10;
});
}Putting async work inside the setState callback
The callback passed to setState must be synchronous. Do the awaiting first, then call setState with the result, as _load does above.
Calling setState inside build
build() can run many times per second. A call to setState from inside it requests another rebuild during a rebuild, which produces an error or an endless loop. Call setState only from event handlers, callbacks, timers, and similar places.
Declaring state in the wrong class
Fields declared on the StatefulWidget class must be final, so they cannot hold changing data. If you find yourself wanting to mutate a widget field, move it to the State class.
Rebuilding too much
setState rebuilds everything returned by that State's build(). In a small screen that is fine. In a large one, extract the part that changes into its own stateful widget, so only that part rebuilds.
callout tip
Flutter rebuilds are cheap, so do not optimize early. Move state down into a smaller widget only when a screen is large or you notice dropped frames.Stateless or stateful?
Use this rule: if the widget's output depends only on the values its parent passes in, make it stateless. If it must remember something between builds, or react to its own events by changing what it shows, make it stateful.
A parent can also own the state and pass the value and a callback down to a stateless child. Choosing where state lives is a design decision you will return to as apps grow. For a single screen with a few values, setState in one State class is the right tool.
Exercises
Exercise
A teammate writes void _reset() { _count = 0; } and wires it to a button. The variable changes but the screen still shows the old number. What is wrong, and what is the fix?
Show answer
The mutation happens outside setState, so Flutter is never told to rebuild. Write void _reset() { setState(() { _count = 0; }); }.
Exercise
Your State class starts a Timer.periodic in initState(). Which method should cancel it, and what error can appear if you skip this?
Show answer
dispose() should call _timer.cancel(). Without it, the timer keeps running after the widget is gone, and a later setState call can throw an error about being called after dispose(). Guarding with if (!mounted) return; also prevents that error.