Flutter Counter with setState: solved exercise step by step

  2 minutes

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

Build a screen with:

  • counter value centered on screen
  • increment button
  • decrement button
  • reset to zero button
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)),
        ],
      ),
    );
  }
}

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

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

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

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

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

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