Thuta Learning
Flutter
IntermediateMobile DevelopmentBeginner

setState

FlutterLesson 1720 min

What you'll walk away with

  • Explain the widget, state, and lifecycle behavior of setState
  • Test responsive, failure, and interaction cases
  • Write accessible, testable, and performant Flutter

Explain it simply

setState, in plain language

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.

Problem → Why → Solution

The problem — why this concept matters

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

A common mistake

Assuming one screen's sample output proves every rebuild, overflow, accessibility, async, and lifecycle path.

Core concept — understand how it works

For setState, define the source of truth, validation, focus, controller disposal, and minimal rebuild boundary. Keep ephemeral state local and place shared app state in a testable controller or model.

Mental model
  1. event
  2. state owner and notifier
  3. rebuilt widgets

Explain the widget, state, and lifecycle behavior of setState

Core syntax or pattern

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'),
        ),
      ],
    );
  }
}

For setState, define the source of truth, validation, focus, controller disposal, and minimal rebuild boundary. Keep ephemeral state local and place shared app state in a testable controller or model.

Read the code step by step

  1. eventclass Counter extends StatefulWidget {

    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.

  2. state owner and notifierWidget build(BuildContext context) {

    For setState, define the source of truth, validation, focus, controller disposal, and minimal rebuild boundary. Keep ephemeral state local and place shared app state in a testable controller or model.

  3. rebuilt widgets}

    Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Execution flow
  1. event
  2. state owner and notifier
  3. rebuilt widgets

Success

Explain the widget, state, and lifecycle behavior of setState

Failure

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

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.

Real-world usage

How to apply it in a real project

Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Mini challenge

Build it yourself

Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
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'),
        ),
      ],
    );
  }
}

Expected: Explain the widget, state, and lifecycle behavior of setState

Show hint

Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Quick quiz 1 / 3

What best describes the core idea of setState?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • event → state owner and notifier → rebuilt widgets
  • For setState, define the source of truth, validation, focus, controller disposal, and minimal rebuild boundary. Keep ephemeral state local and place shared app state in a testable controller or model.
  • If you do counter++ outside of setState() and never call setState(), the UI won't update.
  • Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Flutter documentation — Flutter

Easy traps

  • If you do counter++ outside of setState() and never call setState(), the UI won't update.
  • Assuming one screen's sample output proves every rebuild, overflow, accessibility, async, and lifecycle path.
  • Doing expensive work in build(), leaking controllers or subscriptions, or calling setState over an unnecessarily large subtree.

Hands-on Exercise

Run and test an original setState example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

You'll know it worked when: The screen shows "Count: 0" and a "+ Add" button. Every tap of the button increases the count.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

setState | Thuta Learning