Learn/Advanced State Management/Riverpod

Riverpod

Modern, compile-safe state management with Riverpod

8 min~6 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Riverpod Architecture Strategy
  2. 2. Modern Riverpod 2.0+: Code Generation with @riverpod
  3. 3. Advantages of Riverpod Code Generation:
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Quick Glossary
  11. 11. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Riverpod

Riverpod is a reactive caching and data-binding framework for Flutter. It is the evolution of the Provider package, designed to be fully compile-safe, highly testable, and completely independent of BuildContext. Unlike Provider, Riverpod catches errors at compile time rather than at runtime, supports multiple providers of the same type, and works outside the widget tree. It handles asynchronous data with built-in loading and error states, making it ideal for apps that fetch data from APIs, databases, or other async sources. Riverpod 3.x also supports code generation with the @riverpod annotation for even cleaner syntax.

dart
1// pubspec.yaml: flutter_riverpod: ^2.4.0
2import 'package:flutter_riverpod/flutter_riverpod.dart';
3
4// ── Step 1: Wrap app with ProviderScope ──
5void main() {
6 runApp(const ProviderScope(child: MyApp()));
7}
8
9// ── Simple StateProvider ──
10final counterProvider = StateProvider<int>((ref) => 0);
11
12// ── StateNotifierProvider (for complex state) ──
13class TodoNotifier extends StateNotifier<List<String>> {
14 TodoNotifier() : super([]);
15
16 void add(String todo) => state = [...state, todo];
17 void remove(int index) {
18 state = [...state]..removeAt(index);
19 }
20}
21
22final todoProvider = StateNotifierProvider<TodoNotifier, List<String>>(
23 (ref) => TodoNotifier(),
24);
25
26// ── FutureProvider (for async data) ──
27final userProvider = FutureProvider<User>((ref) async {
28 final response = await http.get(Uri.parse('https://api.example.com/user'));
29 return User.fromJson(jsonDecode(response.body));
30});
31
32// ── Using in widgets ──
33class CounterPage extends ConsumerWidget {
34 @override
35 Widget build(BuildContext context, WidgetRef ref) {
36 final count = ref.watch(counterProvider);
37
38 return Scaffold(
39 body: Center(child: Text('Count: $count')),
40 floatingActionButton: FloatingActionButton(
41 onPressed: () => ref.read(counterProvider.notifier).state++,
42 child: const Icon(Icons.add),
43 ),
44 );
45 }
46}

ref.watch vs ref.read

💡 ref.watch vs ref.read

Use ref.watch() inside the build() method to subscribe to a provider and rebuild the widget whenever the value changes. Use ref.read() inside callbacks like onPressed or onTap to read a value once without subscribing to future changes. Using ref.read() in build() is a common mistake that prevents your widget from updating when state changes.

Riverpod Architecture Strategy

Use Riverpod as a dependency graph, not just a state container:

  • Providers expose one responsibility each (auth state, repository instance, active filters).
  • Business logic lives in Notifier or AsyncNotifier classes, not in widgets.
  • UI reads providers through ref.watch and triggers actions through notifiers.
  • External dependencies are injected via providers so tests can replace them.

This model keeps your app modular and makes unit tests straightforward without widget scaffolding.

Riverpod Pitfalls To Avoid

  • Putting heavy side effects directly inside provider build methods.
  • Using ref.read in build and wondering why UI does not update.
  • Creating overly broad providers that force unnecessary rebuilds.
  • Ignoring provider disposal behavior for screen-scoped state.
  • Mixing mutable state patterns that bypass notifier updates.

Riverpod Adoption Checklist

  • ProviderScope wraps the app root and tests initialize providers correctly.
  • Feature modules define clear provider ownership and naming conventions.
  • Async providers expose clear loading, error, and retry behavior in UI.
  • Repositories are injected and mocked in unit tests without global singletons.
  • Provider rebuild hotspots are profiled and optimized where needed.

Modern Riverpod 2.0+: Code Generation with @riverpod

In modern Flutter development, the Riverpod community has standardized on Code Generation using @riverpod annotations and build_runner. This eliminates manual boilerplate providers like StateNotifierProvider or ChangeNotifierProvider.

import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'counter_notifier.g.dart';

// Generates a type-safe AutoDisposeNotifierProvider:
@riverpod
class CounterNotifier extends _\$CounterNotifier {
  @override
  int build() => 0; // Initial state

  void increment() => state++;
}

// In your UI widget:
class CounterScreen extends ConsumerWidget {
  const CounterScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterNotifierProvider);
    return Scaffold(
      body: Center(child: Text('Count: \$count')),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(counterNotifierProvider.notifier).increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

Advantages of Riverpod Code Generation:

  • No Manual Provider Suffixes: Generates clean, type-safe providers automatically.
  • AutoDispose by Default: Memory is freed as soon as no widgets are listening.
  • AsyncNotifier: Built-in support for loading, error, and data states with AsyncValue.

This Lesson In Simple Words

Modern, compile safe state management with Riverpod. State is data that changes over time and controls what users see on the screen.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Keep state as close as possible to where it is used, then lift it only when sharing is required.

Deep Understanding Guide

Why this lesson matters

State management is the difference between predictable apps and hard-to-debug UI behavior.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Trace one user action from button tap to state update to rebuilt UI.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Calling setState high in the tree when only a small part needs refresh.
  • Keeping duplicated state in multiple widgets without a single source of truth.
  • Mutating collections directly and expecting UI updates automatically.
  • Choosing a heavy state library before understanding simple local state.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one feature with local setState, then refactor it to Provider or Riverpod.
  • Create loading, success, and error states for one async user flow.
  • Write a small state diagram for a login form and implement it.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What must wrap your app to use Riverpod?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • context: A handle to widget location and inherited data in the tree.
  • build: The method that describes UI for the current state.
  • provider: A dependency and state sharing pattern in widget trees.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

State boundaries define module boundaries, so clear ownership prevents future regressions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Riverpod" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Calling setState high in the tree when only a small part needs refresh.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What must wrap your app to use Riverpod?

ProviderScope stores all provider state and must wrap the entire app at the root.

When should you use ref.watch() vs ref.read()?

ref.watch() in build() makes the widget rebuild on changes. ref.read() in callbacks reads once without rebuilding.

Which provider is best for async data like API calls?

FutureProvider automatically handles loading/error/data states for async operations.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue