Riverpod in Flutter: solved counter exercise

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

 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
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 ProviderScope at app root.
  • Using read to render UI instead of watch.
  • Mixing local and shared state without a clear boundary.

Practical use

Riverpod is useful for apps that will grow in screens and shared logic.

Guided practice and next step

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.