Dan Tech Academy

StatelessWidget or StatefulWidget: when setState is enough

The difference between StatelessWidget and StatefulWidget, what setState actually does, when to lift state up, and how to check it with a widget test. Code runs on Flutter 3.47.

Two kinds of widget

In Flutter, everything on screen is a widget, and the widgets you write usually extend one of two classes:

  • StatelessWidget: only shows the data it receives through its constructor. To change what it shows, its parent has to rebuild it with new data.
  • StatefulWidget: comes with a State object that outlives each build. Data in the State can change, and you call setState to tell Flutter to rebuild.

I ran flutter analyze and flutter test on the code in this post with Flutter 3.47.7 (Dart 3.13.5). The latest stable release at the time of writing is 3.47.9.

StatelessWidget: display only

class ScoreLabel extends StatelessWidget {
  const ScoreLabel({super.key, required this.score});

  final int score;

  
  Widget build(BuildContext context) {
    return Text('Score: $score');
  }
}

ScoreLabel doesn't know where the score comes from and can't change it. That makes it easy to read and reuse. The const constructor lets you create constant widgets such as const ScoreLabel(score: 0), and when the parent rebuilds, Flutter skips most of the rebuild work for a constant widget.

StatefulWidget and setState

When the widget itself has to remember a value that changes with user actions, use a StatefulWidget:

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

  
  State<ScoreCounter> createState() => _ScoreCounterState();
}

class _ScoreCounterState extends State<ScoreCounter> {
  int _score = 0;

  void _add() {
    setState(() {
      _score++;
    });
  }

  
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ScoreLabel(score: _score),
        ElevatedButton(onPressed: _add, child: const Text('+1')),
      ],
    );
  }
}

setState does two things: it runs the function you pass to change the data, then marks this widget to be rebuilt on the next frame. If you change _score without calling setState, the value in memory changes but the screen stays the same.

Two common mistakes:

  • Calling setState after the widget has left the tree, usually after an await. Check if (!mounted) return; before calling it.
  • Calling setState inside build. build should read state, not change it.

When setState is enough

The Flutter docs split state into two kinds. Ephemeral state is used by one widget only: the selected tab in a BottomNavigationBar, the current page of a PageView, the progress of a complex animation. App state is shared by many parts of the app, such as the logged-in user or a shopping cart. For ephemeral state, the docs say plainly that using setState in a State class is completely natural.

The docs also say there is no clear-cut rule for telling the two apart. A practical check: if only one widget reads and writes the value, keep it in that widget's State and use setState.

When two widgets need the same value

Say the screen header also has to show the score. Now _score shouldn't live in ScoreCounter anymore. You move the state up to the nearest parent that contains both (lifting state up), and the child only receives the value plus a callback:

class ScoreBoard extends StatelessWidget {
  const ScoreBoard({super.key, required this.score, required this.onAdd});

  final int score;
  final VoidCallback onAdd;

  
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ScoreLabel(score: score),
        ElevatedButton(onPressed: onAdd, child: const Text('+1')),
      ],
    );
  }
}

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

  
  State<MatchScreen> createState() => _MatchScreenState();
}

class _MatchScreenState extends State<MatchScreen> {
  int _score = 0;

  
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Header: $_score'),
        ScoreBoard(score: _score, onAdd: () => setState(() => _score++)),
      ],
    );
  }
}

ScoreBoard is now a StatelessWidget. Only MatchScreen holds the state, so the header and the board always show the same number.

This still uses only setState. It gets uncomfortable when state has to pass through many widget layers that don't use it, or when several different screens need it. That is the point to move state out of widgets with ChangeNotifier or a state management library.

Check it with a widget test

testWidgets('tapping +1 updates the score', (tester) async {
  await tester.pumpWidget(const MaterialApp(home: Scaffold(body: ScoreCounter())));

  expect(find.text('Score: 0'), findsOneWidget);
  await tester.tap(find.text('+1'));
  await tester.pump();
  expect(find.text('Score: 1'), findsOneWidget);
});

tester.pump() runs one frame, which is the rebuild setState just asked for. Remove that line and the second expect fails, because the screen hasn't been rebuilt yet.

Keep learning

Flutter Mobile 101 teaches Dart and widget fundamentals on a complete app repo: clone it, run it, read it, then change it piece by piece.

Reading is fun. A roadmap gets you there.

The Kotlin Android Roadmap sorts the Android Mastery, OOP and Design Patterns posts into 5 levels - from your first line of Kotlin to an app on the store.

Plus a new post every week. Unsubscribe anytime.