Flutter Counter with setState: solved exercise step by step

Flutter Counter with setState: solved exercise

If you are looking for Flutter counter with setState, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Problem statement

Build a screen with:

  • counter value centered on screen
  • increment button
  • decrement button
  • reset to zero button

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: CounterPage());
  }
}

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

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

class _CounterPageState extends State<CounterPage> {
  int counter = 0;

  void increment() => setState(() => counter += 1);
  void decrement() => setState(() => counter -= 1);
  void reset() => setState(() => counter = 0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Contador con setState')),
      body: Center(
        child: Text('$counter', style: const TextStyle(fontSize: 48)),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(onPressed: increment, child: const Icon(Icons.add)),
          const SizedBox(height: 8),
          FloatingActionButton(onPressed: decrement, child: const Icon(Icons.remove)),
          const SizedBox(height: 8),
          FloatingActionButton(onPressed: reset, child: const Icon(Icons.refresh)),
        ],
      ),
    );
  }
}

Expected result

The counter updates instantly on each button tap without reloading the app.

Common mistakes

  • Updating state outside setState.
  • Mixing local and global state too early.
  • Putting too much logic directly inside build.

Practical use

This pattern appears in quick interactive flows like votes, likes, filters, and small form steps.

Guided practice and next step

FAQ

When should I use setState in Flutter?

Use it when state is local to one widget tree and does not need global sharing.

Is Provider better than setState?

For global shared state, usually yes. For simple local updates, setState is often the right tool.

Is this useful for Flutter interviews?

Yes. It validates your understanding of state changes and UI rebuild behavior.