Sub topic 7
Changing the UI with `setState`
Assume you know basic Dart classes, constructors, final fields, named parameters, and null safety. You also have Flutter installed and can run a simple app.
A StatefulWidget is a widget whose UI can change while the app runs. The widget itself remains immutable. Its separate State object stores changing values. When a value changes, call setState to tell Flutter that the UI may need to be rebuilt.
The working model
The setState method accepts a synchronous callback. Put the state mutation inside that callback:
setState(() {
_count++;
});Flutter runs the callback and schedules the State object's build method again. The rebuilt method reads the new value and returns updated widgets.
Calling setState does not directly change a Text widget. It marks the state as needing a rebuild. Flutter then decides when to perform that rebuild during its rendering process.
A complete example
This app displays a counter and increases it when the button is pressed:
import 'package:flutter/material.dart';
void main() {
runApp(const CounterApp());
}
class CounterApp extends StatelessWidget {
const CounterApp({super.key});
@override
Widget build(BuildContext context) {
return 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;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text(
'Count: $_count',
style: const TextStyle(fontSize: 32),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
child: const Icon(Icons.add),
),
);
}
}The _count field belongs to _CounterPageState, so it survives ordinary rebuilds. The build method reads _count. The button calls _increment, which changes _count inside setState.
Common errors
| Error | Result | Better approach |
|---|---|---|
| Change a field without `setState` | The field changes, but the screen may stay unchanged | Wrap the mutation in `setState` |
| Put slow work inside `setState` | Rebuild scheduling becomes harder to reason about | Do the work first, then update state |
| Call `setState` after the State is removed | Flutter reports that the State is no longer mounted | Cancel work or check `mounted` before updating |
| Call `setState` unnecessarily | More widgets may rebuild than needed | Update only when the value actually changes |
For example, after an awaited request, use if (!mounted) return; before calling setState. This prevents an update after the user has navigated away and the State has been disposed.
Exercise
Why does changing _count without calling setState fail to reliably update the displayed Text?
Show answer
Flutter is not notified that the State needs rebuilding, so the existing widget tree can continue displaying the old value.