Skip to the workspace
Pebellslearn by building
Widgets  ›  Lesson

Stateful Widgets

Stateful Widgets 12 minA stateful widget pairs an immutable widget with a long-lived State object, and calling setState inside that object marks it dirty so its build method runs again.

flutter / Stateful Widgets

Explore each scene at your own pace.

01 · The rule

The rule

Stateful Widgets

Tapping "Watered" on the fern should tick it off and update the count on screen. That widget must remember something between frames and redraw when it changes. Stateless widgets cannot do that; stateful widgets are built for it.

The rule

Change the value inside setState, and Flutter runs build again.

A stateful widget is two classes:

class WaterCounter extends StatefulWidget {
  const WaterCounter({super.key, required this.plant});
  final String plant;

  @override
  State<WaterCounter> createState() => _WaterCounterState();
}

class _WaterCounterState extends State<WaterCounter> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () => setState(() => count++),
      child: Text('${widget.plant}: watered $count times'),
    );
  }
}
  • The widget class is immutable, like any widget. It holds the inputs, here plant.
  • The State class is created once by createState and lives as long as the widget stays in the tree. The changing value, count, belongs here.
  • Inside the State, widget.plant reads the widget's inputs.
  • setState runs your change and marks the State as needing a rebuild, so build runs again with the new value.

Two lifecycle methods matter early: initState runs once when the State is created (set up controllers or timers there), and dispose runs when it is removed (clean them up there).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.