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
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.
Recommended next exercise
- FutureBuilder in Flutter: solved exercise for loading states
- Provider in Flutter for global state: solved exercise
- BottomNavigationBar in Flutter: solved exercise with IndexedStack
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
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.