Sub topic 7
Changing the UI with setState
This chapter covers how setState turns a data change into a new frame. It assumes you know basic Dart (classes, final fields, named parameters), null safety, and how to run a simple Flutter app. It also assumes you have seen a StatefulWidget and its State class. The goal is a working model of what setState does, plus the errors that come up most often.
What setState does
A State object holds mutable data in its fields. Changing a field does not change the screen. Flutter redraws only when the framework knows the State is out of date, and setState is how you tell it.
Calling setState does two things:
- It runs the callback you pass, synchronously and immediately.
- It marks the
State's element as dirty, so the framework schedules a call tobuildbefore the next frame.
The framework does not call build inside setState. Many calls to setState in the same event can lead to one build, because the element is already marked dirty after the first call.
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'),
);
}
}Tapping the button runs _increment. The callback raises _count from 0 to 1, and the framework then calls build. build returns a new ElevatedButton whose Text reads Count: 1.
The Counter widget itself never changes. It is immutable. The _CounterState object lives on between rebuilds and holds _count.
The update cycle
The sequence from tap to new pixels has several steps.
Each frame, the framework rebuilds the dirty elements. The new widget subtree is compared with the old one, and only the parts that differ cause changes to the render objects that paint the screen. You can call setState often without redrawing the whole screen, as long as build stays cheap.
Where to change the data
The callback you pass to setState is the right place to change the fields that build reads. The framework also marks the element dirty if you change the field outside the callback and then call setState(() {}). That works, but it hides the intent. Putting the mutation inside the callback makes it clear which state changed, and it keeps the change and the rebuild request together.
void _reset() {
setState(() {
_count = 0;
});
}Keep the callback short and synchronous. It must not do slow work such as reading a file or calling a network API. Do that work first, then call setState with the result.
setState and asynchronous work
A common pattern is to load data, then show it. The await happens outside setState, and the state change happens inside.
import 'package:flutter/material.dart';
class Profile extends StatefulWidget {
const Profile({super.key});
@override
State<Profile> createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
String? _name;
bool _loading = false;
Future<String> _fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
Future<void> _load() async {
setState(() {
_loading = true;
});
final name = await _fetchName();
if (!mounted) return;
setState(() {
_name = name;
_loading = false;
});
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const CircularProgressIndicator();
}
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_name ?? 'No name yet'),
ElevatedButton(onPressed: _load, child: const Text('Load')),
],
);
}
}This example calls setState twice. The first call shows the spinner right away. The second call runs after the future completes and shows the result.
The mounted check matters. While the await is pending, the user may leave the screen, which removes the State from the tree and disposes it. After that, calling setState throws an error. mounted is true while the State is in the tree, so returning early when it is false avoids the error.
Rules for calling setState
Where you call setState matters as much as how.
| Where | Allowed? | Notes |
|---|---|---|
| Event handlers (`onPressed`, `onChanged`) | Yes | The normal case. |
| After an `await`, guarded by `mounted` | Yes | Check `mounted` first. |
| Inside a stream or timer callback | Yes | Cancel the subscription or timer in `dispose`. |
| Inside `build` | No | Triggers a rebuild loop or an assertion error. |
| Inside `initState` | Not needed | Set fields directly. No build has run yet. |
| After `dispose` | No | Throws. |
In initState, assign the initial values to fields directly. build has not run yet, so there is nothing to mark dirty. A call to setState there is unnecessary and the framework discourages it.
Mutating objects and lists
setState does not compare old and new values. It always schedules a rebuild. Because of that, mutating a list in place works:
setState(() {
_items.add('new item');
});The rebuild happens, and build reads the changed list. This works for widgets that read _items directly in build. It can fail when a child widget receives the same list object and decides, based on identity or equality, that nothing changed. For example, a child that uses identical(oldWidget.items, widget.items) in didUpdateWidget will see no difference after an in-place add.
Creating a new list avoids that problem:
setState(() {
_items = [..._items, 'new item'];
});The new list has a different identity, so any comparison against the old one reports a change. This habit also prepares you for state management packages that compare values to decide on updates. Use the first form for simple local state, and the second whenever another part of the code compares collections.
Children rebuild too
When setState runs, build runs for that State. Every widget that build creates is new, so the framework asks each child whether it needs to update. Children that are const instances are the same object as before, so the framework skips them.
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Total'),
Text('$_count'),
],
);
}The first Text is const and is reused. The second Text depends on _count, so it is created again on every build. In a small tree the cost is negligible. In a large tree, call setState as low as you can. Move the changing part into its own small StatefulWidget, so that only that subtree rebuilds.
Common errors
- No visible change. You modified a field outside
setStateand never called it. The data changed, but nothing scheduled a build. - Error after leaving a screen. A future or timer finished after
disposeand calledsetState. Checkmounted, or cancel the timer indispose. - "setState() or markNeedsBuild() called during build." You called
setStateon a widget while the tree was being built, for example from withinbuildor a child'sbuild. Move the call to an event handler or schedule it after the frame. - State lost on rebuild. You declared a variable inside
buildinstead of as a field on theState. Local variables inbuildare recreated on each call, so they reset. - Slow UI.
setStatesits on a large widget near the root of the screen, so a small change rebuilds a large subtree.
Here is the fourth mistake in code:
class _BrokenCounterState extends State<BrokenCounter> {
@override
Widget build(BuildContext context) {
int count = 0; // Reset to 0 on every build.
return ElevatedButton(
onPressed: () => setState(() => count++),
child: Text('Count: $count'),
);
}
}The button always shows 0, because count starts over each time build runs. The fix is to move count out of build and into a field of the class, as in _CounterState earlier.
Summary of the model
setState runs your callback, marks the element dirty, and lets the framework call build before the next frame. It does not compare values and does not call build itself. Keep callbacks short, guard asynchronous work with mounted, avoid calling it from build, and keep the rebuilt subtree small.
Exercise
A State method awaits a network call and then runs setState(() => _data = result);. Users sometimes see the error "setState() called after dispose()" after pressing the back button. What causes it, and what is the fix?
Show answer
The user leaves the screen while the request is pending, so the framework disposes the State. When the future completes, setState runs on a disposed State and throws. The fix is to add if (!mounted) return; after the await and before setState. Cancelling the work in dispose, where the API supports it, also helps.
Exercise
A widget's build method declares final items = <String>[]; and an onPressed handler calls setState(() => items.add('x')). The list never grows on screen. Why, and how do you fix it?
Show answer
items is a local variable inside build, so each rebuild creates a new empty list and the earlier addition is lost. Move items to a field of the State class, so the same list persists across rebuilds, and keep the setState call that modifies it.