Thuta Learning
IntermediateMobile Developmentbeginner

setState

Relax. We'll talk through this in plain words — no textbook voice.

setState() is the basic way to change state inside a StatefulWidget and tell it to rebuild the UI. It's commonly used for things like incrementing a counter on button press, showing a message after a form submits, or toggling a switch. For small to medium UI updates, setState() is all you need.

dart
class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('Count: $counter'),
        ElevatedButton(
          onPressed: incrementCounter,
          child: const Text('+ Add'),
        ),
      ],
    );
  }
}
You should see
The screen shows "Count: 0" and a "+ Add" button. Every tap of the button increases the count.

Next Steps

Once you've got state updates down, move on to Navigation — moving from one screen to another.

Easy traps

  • If you do counter++ outside of setState() and never call setState(), the UI won't update.
setState | Thuta Learning