Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 73 ยท State management

Riverpod

Learn Riverpod in Flutter: providers, ref.watch and ref.read, Notifier and AsyncNotifier, family, autoDispose, and overriding providers in tests.

Provider looks objects up by type through the widget tree, so a missing provider is only found at runtime and everything must live under a widget. Riverpod, written by the same author, keeps the good ideas and moves the providers out of the widget tree. Providers become global, final variables that describe how to compute a value; the framework caches, shares and disposes the values for you.

Riverpod gives you compile-time safety (no "provider not found"), built-in handling of async data, easy testing through overrides, and dependencies between providers that update automatically.

Real vs stand-in. Riverpod (flutter_riverpod) is a package and cannot run on this site, so its Dart is read-only. The JavaScript example is a stand-in: a tiny provider graph with caching, dependencies, family and overrides, to show what the library does behind ref.watch. Check the package docs for the exact API of your installed major version; the concepts here are stable.

Why Riverpod

Compile-safe No lookup by type at runtime.
Not tied to widgets Providers are plain globals.
Async built in Loading, data, error.
Easy tests Override any provider.
1 / 2

Setup

YAML
dependencies:
  flutter_riverpod: ^3.0.0

Wrap the app in a ProviderScope, which stores the state of all providers:

DART
void main() {
  runApp(const ProviderScope(child: MyApp()));
}

Simple providers

A Provider exposes a value that is computed once and cached:

DART
final greetingProvider = Provider<String>((ref) => 'Hello');

final apiClientProvider = Provider<ApiClient>((ref) => ApiClient());

Providers can depend on each other using ref.watch. When a watched provider changes, the dependent one is recomputed:

DART
final repositoryProvider = Provider<ProductRepository>((ref) {
  final api = ref.watch(apiClientProvider);
  return ProductRepository(api);
});

Notifier: state with methods

For state that changes, extend Notifier<T>. The build method returns the initial state, and you update state (which notifies watchers when you assign a new value):

DART
class CartNotifier extends Notifier<List<Product>> {
  @override
  List<Product> build() => const [];

  void add(Product product) {
    state = [...state, product];        // new list: watchers are notified
  }

  void remove(String id) {
    state = state.where((p) => p.id != id).toList();
  }
}

final cartProvider =
    NotifierProvider<CartNotifier, List<Product>>(CartNotifier.new);

final cartTotalProvider = Provider<double>((ref) {
  final items = ref.watch(cartProvider);
  return items.fold(0, (sum, p) => sum + p.price);
});

State is immutable by convention: always assign a new object, as with ValueNotifier.

Using providers in widgets

Widgets that need ref extend ConsumerWidget (or ConsumerStatefulWidget):

DART
class CartPage extends ConsumerWidget {
  const CartPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final items = ref.watch(cartProvider);          // rebuild on change
    final total = ref.watch(cartTotalProvider);

    return Column(
      children: [
        Expanded(
          child: ListView(
            children: [
              for (final p in items)
                ListTile(
                  title: Text(p.name),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () =>
                        ref.read(cartProvider.notifier).remove(p.id),
                  ),
                ),
            ],
          ),
        ),
        Text('Total: $total'),
      ],
    );
  }
}

The same watch/read split as in Provider applies:

  • ref.watch: use in build (and inside providers) to rebuild or recompute when the value changes.
  • ref.read: use in callbacks to read once or call a method (ref.read(cartProvider.notifier).add(p)). Never in build.
  • ref.listen: run a side effect when a value changes (show a snackbar, navigate), without rebuilding.
  • ref.watch(provider.select((s) => s.count)): rebuild only when the selected part changes.

Async data with AsyncNotifier

Network data is the most common use. An AsyncNotifier returns a Future from build, and the state is an AsyncValue<T> with three cases: loading, data and error.

DART
class ProductsNotifier extends AsyncNotifier<List<Product>> {
  @override
  Future<List<Product>> build() {
    return ref.watch(repositoryProvider).fetchProducts();
  }

  Future<void> refresh() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(
      () => ref.read(repositoryProvider).fetchProducts(),
    );
  }
}

final productsProvider =
    AsyncNotifierProvider<ProductsNotifier, List<Product>>(ProductsNotifier.new);

In the UI, when forces you to handle every case:

DART
final products = ref.watch(productsProvider);

return products.when(
  loading: () => const Center(child: CircularProgressIndicator()),
  error: (error, stack) => Text('Failed: $error'),
  data: (list) => ProductGrid(products: list),
);

AsyncValue.guard runs a future and turns a thrown exception into an AsyncError, so you never write try/catch around every call. For a read-only async value with no methods, FutureProvider is simpler.

family and autoDispose

Two modifiers turn a provider into a more flexible one.

family makes a provider that takes a parameter. Each distinct argument gets its own cached state:

DART
final productProvider = FutureProvider.family<Product, String>((ref, id) {
  return ref.watch(repositoryProvider).fetchProduct(id);
});

// In a widget:
final product = ref.watch(productProvider('p-42'));

autoDispose destroys the state when nobody watches the provider any more, so a detail screen's data is released when you leave it. Combine them:

DART
final searchProvider =
    FutureProvider.autoDispose.family<List<Product>, String>((ref, query) {
  return ref.watch(repositoryProvider).search(query);
});

Without autoDispose, a provider keeps its state for as long as the ProviderScope lives. Use it for screen-specific data and keep long-lived data (user session, settings) permanent.

Stand-in: a provider graph

The code below rebuilds the core ideas: providers described by functions, a cache, dependencies through watch, invalidation, family keyed by argument, and overrides for tests.

JS A mini provider graph with overrides

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can see the three promises of the library: values are computed once and cached, a change in a dependency recomputes only what depends on it, and swapping a leaf provider (the API client) changes the whole chain without touching the code under test.

Testing with overrides

Because providers are global descriptions, a test creates its own scope and replaces any of them:

DART
testWidgets('shows fake products', (tester) async {
  await tester.pumpWidget(
    ProviderScope(
      overrides: [
        repositoryProvider.overrideWithValue(FakeRepository()),
      ],
      child: const MaterialApp(home: ProductsPage()),
    ),
  );
  await tester.pump();
  expect(find.text('Fake tea'), findsOneWidget);
});

For tests without widgets, create a container: final container = ProviderContainer(overrides: [...]); and call container.read(...). Testing is covered in Unit and widget testing.

Pitfalls

  • ref.read in build. The widget will not update. Use watch.
  • ref.watch in a callback. Not allowed. Use read.
  • Mutating state. state.add(x) keeps the same list object; assign a new one.
  • Forgetting autoDispose on per-screen data, so stale values appear when you return to a screen.
  • Putting side effects in build of a provider. Provider functions can re-run any time; keep them free of one-off actions such as navigation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a ProviderScope do?

    ProviderScope holds the provider container. Without it ref.watch has nothing to read from.
  2. 2. Which call belongs in an onPressed handler to add an item to the cart notifier?

    Use read in callbacks to reach the notifier and call its methods. Watch is for build.
  3. 3. What does autoDispose do?

    When the last listener goes away, the state is released, which suits per-screen data.
  4. 4. How does AsyncValue.when help?

    AsyncValue models the three states, and when requires a branch for each.

Summary

  • Riverpod providers are global declarations; ProviderScope stores their state.
  • Use Provider, NotifierProvider, AsyncNotifierProvider and FutureProvider; keep state immutable and assign new objects.
  • ref.watch in build and in other providers, ref.read in callbacks, ref.listen for side effects.
  • family adds parameters, autoDispose frees unused state; AsyncValue models loading, data and error.
  • Overrides make testing easy: replace a leaf provider and the graph follows.

Next: BLoC and Cubit