Riverpod in Flutter: solved exercise
If you need a Riverpod Flutter solved example, this exercise gives you a clean baseline for shared state without relying on setState in the root widget.
Problem statement
Build an app with:
- visible counter value,
- increment button,
- state handled through Riverpod.
Flutter solution
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final counterProvider = StateProvider<int>((ref) => 0);
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: CounterPage());
}
}
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(title: const Text('Riverpod Counter')),
body: Center(child: Text('Value: $count', style: const TextStyle(fontSize: 24))),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).state++,
child: const Icon(Icons.add),
),
);
}
}Expected result
Each tap adds 1 and updates the UI immediately.
Common mistakes
- Forgetting
ProviderScopeat app root. - Using
readto render UI instead ofwatch. - Mixing local and shared state without a clear boundary.
Practical use
Riverpod is useful for apps that will grow in screens and shared logic.
Recommended next exercise
- Provider in Flutter for global state: solved exercise
- FutureBuilder in Flutter: solved exercise
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Is Riverpod better than Provider for beginners?
It depends on project needs, but Riverpod often scales better and avoids context-related pitfalls.
Which provider should I use for a simple counter?
StateProvider<int> is enough for this use case.
Is this pattern production-ready?
Yes. It is a solid starting point for larger state models.