Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 73 ยท Widgets and the widget tree

StatefulWidget and setState

Learn Flutter StatefulWidget: the State object, how setState marks a widget dirty and triggers a rebuild, and the lifecycle with initState, didUpdateWidget and dispose.

A StatelessWidget shows what it is given. But real screens change: a counter goes up, a checkbox flips, a text field fills, a spinner stops. Anything that changes while the widget is on screen, and is owned by that widget, is called state. Flutter gives you StatefulWidget for it.

A stateful widget is really two classes: an immutable widget, and a separate State object that lives for as long as the widget stays mounted. You change the data inside the State and call setState, which tells Flutter "my description is out of date, please call build again". This lesson explains that cycle, the lifecycle methods, and the classic mistakes. It builds on Everything is a widget and the three trees.

Real vs stand-in. The Dart is real Flutter code, read-only here. The live examples are JavaScript stand-ins for the dirty-marking engine: they show when build runs, when it does not, and in what order lifecycle hooks fire.

The setState cycle

Event A tap, a timer, a response.
setState Change data inside the callback.
Mark dirty Flutter flags this element.
Rebuild build runs again next frame.
1 / 2

A counter

DART
class CounterPage extends StatefulWidget {
  const CounterPage({super.key, this.start = 0});

  final int start;

  @override
  State<CounterPage> createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  late int _count = widget.start;

  void _increment() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text('Taps: $_count')),
      floatingActionButton: FloatingActionButton(
        onPressed: _increment,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Read the pieces:

  • CounterPage is the widget. Its fields are final, like any widget. It creates its State with createState.
  • _CounterPageState holds _count. The leading underscore makes the class private to the file.
  • Inside State, widget refers to the current CounterPage instance (the latest configuration from the parent). Here widget.start provides the initial value.
  • setState(() { ... }) runs your closure immediately and synchronously, then marks the element dirty. Flutter schedules a frame, and on that frame build runs again with the new _count.

The widget instance is thrown away and recreated whenever the parent rebuilds, but the same _CounterPageState object is kept by the element (see the element tree). That is why _count survives.

What setState does and does not do

setState does not put the value in some magic storage. It only does two things: calls your function, and marks the element dirty. If you change _count without setState, the variable changes but nothing redraws:

DART
void _incrementBroken() {
  _count++; // the field changes, the screen does not
}

The reverse mistake is also common: putting heavy work inside the callback. Keep the closure to quick assignments and do computation before it.

DART
Future<void> _load() async {
  final data = await repository.fetch();   // do the async work first
  if (!mounted) return;                    // the widget may be gone
  setState(() {
    _items = data;                         // then only assign
  });
}

setState can never take an async closure. And calling it after dispose throws an error, which is why you check mounted after any await.

Stand-in: a dirty-marking engine

The engine below mimics what the framework does. setState runs the update, marks the element dirty, and the "frame" rebuilds only dirty elements, no matter how many times setState was called before it.

JS setState marks dirty; the frame rebuilds once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three setState calls change the count to 3, but there is only one extra build. Then we set the field to 100 without calling setState: the state is 100, the screen still shows Taps: 3. That mismatch is exactly the bug you get in Flutter when you forget setState.

The State lifecycle

A State object goes through a fixed lifecycle. The methods you override, in order:

  1. createState on the widget: the framework creates the State.
  2. initState: called once, when the State is inserted. Set up controllers, subscriptions and initial data. Always call super.initState() first. You can use widget here but not context.dependOnInheritedWidgetOfExactType (the lookup in BuildContext and InheritedWidget is not allowed yet).
  3. didChangeDependencies: called right after initState and again whenever an inherited widget this State depends on (like Theme or MediaQuery) changes.
  4. build: called many times, whenever the State is dirty or the parent rebuilds it.
  5. didUpdateWidget(oldWidget): called when the parent rebuilt and supplied a new widget instance to the same State. Compare oldWidget and widget to react to changed configuration.
  6. deactivate and dispose: called when the State is removed for good. dispose is where you cancel timers, close stream controllers and dispose controllers. Call super.dispose() last.
DART
class _ClockState extends State<Clock> {
  late final Timer _timer;
  DateTime _now = DateTime.now();

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      setState(() => _now = DateTime.now());
    });
  }

  @override
  void dispose() {
    _timer.cancel();     // otherwise setState would be called after dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text('${_now.hour}:${_now.minute}:${_now.second}');
  }
}

If you leave out _timer.cancel(), the timer keeps firing and calls setState on a State that no longer exists. In a debug build Flutter reports it; in the worst case you leak memory. The same rule covers AnimationController, TextEditingController, ScrollController, FocusNode and stream subscriptions (see Futures, async/await and Streams).

JS Lifecycle order for a stateful element

Press Run (or Ctrl + Enter) to see the console output here.

No output.

initState and dispose run once each, around any number of build calls. A parent rebuild causes didUpdateWidget plus build but never a second initState.

Keep the rebuild small

setState rebuilds the whole build method of that State and everything below it. For a tiny counter that is irrelevant. For a big screen, move the changing part into its own small stateful widget so only it rebuilds:

DART
// Better: only the counter label rebuilds when it ticks.
Scaffold(
  appBar: AppBar(title: const Text('Dashboard')),
  body: Column(
    children: const [
      HeavyChart(),      // const: skipped on rebuilds
      TapCounter(),      // owns its own state
    ],
  ),
)

Where state should live, and how to share it between widgets, is the subject of Lifting state up and ValueNotifier.

Common mistakes

  • Mutating state outside setState. The UI does not update.
  • Calling setState in build. It triggers another build, causing an infinite loop or an error.
  • Calling setState after dispose. Cancel timers and subscriptions; check mounted after await.
  • Doing slow work in initState synchronously. Start it asynchronously and show a loading state (FutureBuilder, StreamBuilder and async UI).
  • Forgetting to dispose controllers. Pair every created controller with a dispose call.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does setState actually do?

    setState runs the closure and marks the element dirty. The State object itself is kept.
  2. 2. Which method runs exactly once when a State object is inserted into the tree?

    initState is called once. build and didUpdateWidget can run many times.
  3. 3. Where should you cancel a Timer or a StreamSubscription created in initState?

    dispose is called when the State is permanently removed; it is the place to release resources.
  4. 4. A parent rebuilds and passes a different title to your StatefulWidget. Which State method tells you about the change?

    didUpdateWidget receives the old widget so you can compare it with the new one. The State object is reused.
  5. 5. You change _count++ without calling setState. What happens?

    Only setState (or another dirty-marking call) schedules a rebuild. The variable changes but the UI is stale.

Summary

  • A StatefulWidget is an immutable widget plus a long-lived State object that holds mutable data.
  • setState(() { ... }) runs your closure and marks the element dirty; Flutter rebuilds it on the next frame, and multiple calls are batched.
  • Lifecycle: initState once, didChangeDependencies, build many times, didUpdateWidget when the parent supplies a new widget, dispose once.
  • Release controllers, timers and subscriptions in dispose, and check mounted after await.
  • Keep stateful parts small so rebuilds stay cheap.

Next: Keys and Widget Identity