Sub topic 11
What `setState` Really Does
This chapter assumes basic Dart, StatelessWidget, StatefulWidget, and common widgets such as Column and Text. You will trace how a user action changes a State object and causes Flutter to rebuild part of the widget tree.
A state change starts with `setState`
A State object stores mutable data for a StatefulWidget. Calling setState tells Flutter that this data changed and that the widget's build method should run again.
The callback passed to setState runs immediately. After the callback finishes, Flutter marks the widget's element as dirty. A dirty element is one that needs rebuilding. Flutter normally performs that rebuild during the build phase of a frame.
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;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: _increment,
child: const Text('Increment'),
),
],
),
),
);
}
}When the button is pressed, _count changes synchronously. Flutter then schedules this StatefulElement for rebuilding. Its build method creates a new widget subtree containing the new text. Flutter compares that subtree with the existing one and reuses matching elements where possible.
The State object is not recreated for every rebuild. The same state and element remain attached while the widget's runtime type and key continue to match.
Common mistakes
- Do not make the
setStatecallbackasync. Finish the state update synchronously, then perform asynchronous work separately. - Do not call
setStateafter the state has been disposed. Checkmountedafter an asynchronous operation. - Do not call
setStatefrombuild. Build should describe the UI, not trigger another build. - Call
setStatearound the smallest state change that affects the UI. It marks the whole stateful element dirty, although Flutter may still reuse much of its child tree.
A practical mental model
Think of setState as a notification to the owning StatefulElement:
- Run the callback now.
- Mark the element dirty.
- Re-run
buildduring the frame pipeline. - Reconcile the new widgets with existing elements.
- Perform later layout and paint work only where necessary.
Exercise
Why does the counter's State object survive after _count changes?
Show answer
setState marks the existing StatefulElement dirty. Flutter rebuilds it in place, so its existing State object remains attached.