Sub topic 10
Adding Interaction with `StatefulWidget` and `setState`
Assume you know variables, functions, classes, and basic Flutter widgets. You should also have a Flutter project that runs on a device or emulator. In this chapter, you will keep a value in a widget and update the screen when a button is pressed.
The working model
A StatelessWidget describes UI that depends only on its inputs. A StatefulWidget is used when UI must change during the widget's lifetime. The widget itself is usually permanent configuration. Its separate State object stores changing data.
setState tells Flutter that the state changed and that the widget needs to rebuild. Flutter then calls the build method again. The method reads the new state and returns updated widgets.
A complete counter screen
Replace lib/main.dart with this example:
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: 'Counter',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
),
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 += 1;
});
}
@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),
),
);
}
}CounterPage declares the widget type. _CounterPageState owns _count and the _increment method. The underscore makes these members private to the Dart library.
The createState method connects the widget to its state object. Flutter can recreate the CounterPage configuration while preserving the state when the widget remains in the same location in the widget tree.
The closure passed to setState changes _count. Keep the mutation inside that closure. Flutter schedules a rebuild after the closure finishes. The string interpolation in 'Taps: $_count' then displays the current value.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| The value changes in memory but not on screen | The change happened outside `setState` | Wrap the change in `setState` |
| `setState() called after dispose()` | An asynchronous callback finished after the page was removed | Check `mounted` before updating |
| `setState() or markNeedsBuild() called during build` | State changed while Flutter was already building | Move the change to a callback or later event |
| State unexpectedly resets | A new stateful widget was created in a different tree position | Keep stable widget structure and use keys when list identity requires them |
Do not call setState for values that do not affect this widget's visible output. Also avoid placing expensive work inside build; Flutter may call it many times.
> callout note > setState does not update every widget in the application. It marks this State object for rebuilding. Data shared by several screens usually belongs in a higher-level state object or a state-management package. >
Exercise
Why does changing _count without calling setState usually leave the displayed number unchanged?
Show answer
Flutter does not know that the value changed, so it does not schedule another call to build.