Skip to main content

02 - Riverpod in Depth: AsyncNotifier, Codegen and Testing

With @riverpod, build_runner generates the provider: AsyncNotifier, the three AsyncValue states, watch versus read, and tests with overrideWithValue.

What do you think about this article?

At a Glance

With @riverpod, build_runner generates the provider: AsyncNotifier, the three AsyncValue states, watch versus read, and tests with overrideWithValue.

With code generation you no longer declare a provider: you declare a function or a class and put @riverpod on top of it. The generator derives the typed provider from it, and the name you will use in the widget - productsListProvider - is not written by you, it comes from the name of the class. The gain is that a wrong type becomes a compile-time error instead of a late initialization error at runtime.

The cost is one more build step and a .g.dart file next to each source file. This article builds a complete feature - a product list with loading, error and reload - and then tests it by replacing the repository, which is the thing Riverpod does better than anyone.

The code was not run, the versions are measured

The Dart examples were not compiled: they require build_runner and the generation of the .g.dart files, and that was not run in this environment. They are written against the Riverpod documentation linked at the bottom.

The version numbers in the pubspec, on the other hand, are measured by querying the pub.dev API on 2026-11-08 - command at the bottom - and they matter, because three of them were off by a major version in the previous version of this article.

The dependencies, with the real numbers

This is the part that ages worse than any other and that costs you your first afternoon. The Riverpod packages do not share the major version number, and taking it for granted is the mistake.

pubspec.yaml - versions detected on 2026-11-08
dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: ^3.5.0        # published 2026-11-06
  riverpod_annotation: ^4.0.8     # WARNING: major 4, not 3

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.17.1
  riverpod_generator: ^4.0.10     # WARNING: major 4, not 3
  riverpod_lint: ^3.2.0
  custom_lint: ^0.7.0
  mocktail: ^1.0.5
  freezed: ^4.0.3                 # WARNING: major 4, not 2
  freezed_annotation: ^3.0.0      # optional, only if you use Freezed

The three lines with the warning are the ones the previous version of this article got wrong: it declared riverpod_annotation: ^3.0.0, riverpod_generator: ^3.0.0 and freezed: ^2.4.0. Today the first two are at major version 4 and Freezed is at 4, so those constraints exclude the current versions and pub get resolves to old releases - or fails because of a conflict with flutter_riverpod 3.5.

The general lesson is worth more than the numbers: riverpod and flutter_riverpod go together, but riverpod_annotation and riverpod_generator have their own numbering and must be aligned with each other. When something does not generate, the first thing to check is this pair.

Note also that plain riverpod does not appear: in a Flutter app you need flutter_riverpod, which includes it. Declaring both is not an error but it is pointless, and it increases the chances of keeping them at mismatched versions.

Generating the files, and the correct form of the command
# During development: regenerates on every save, incrementally
dart run build_runner watch --delete-conflicting-outputs

# Just once, for example in CI before the tests
dart run build_runner build --delete-conflicting-outputs

The form is dart run build_runner. The old flutter pub run build_runner still works - on Flutter 3.44.2 it forwards to dart pub run, verified by running it - but dart run is the form used by the build_runner documentation and the one to write in new projects.

--delete-conflicting-outputs is not a convenience option: it is needed when a generated file already exists and the generator wants to rewrite it, which happens after every class rename. Without it, the build stops and asks what to do, and in CI it stops with nobody to answer.

The difference between watch and build is the cost: watch regenerates only the files you touched and keeps running, build starts from scratch. In development you use the first; the second goes in CI, before the tests, because the .g.dart files are usually not committed and without that step the tests do not compile.

From the repository to the provider

The structure that follows has a precise purpose: to make sure the widget does not know where the data comes from. It is what makes the test in the final section possible.

The domain: the model and the repository interface
// domain/product.dart
class Product {
  const Product({
    required this.id,
    required this.name,
    required this.price,
    required this.inStock,
  });

  final String id;
  final String name;
  final double price;
  final bool inStock;
}

// domain/product_repository_interface.dart
// The provider will depend on THIS, not on the implementation
abstract interface class ProductRepositoryInterface {
  Future<List<Product>> fetchProducts();
  Future<Product> createProduct(Product product);
}

The abstract interface is the only truly architectural line in the whole article. By declaring that the provider depends on ProductRepositoryInterface and not on the concrete class that speaks HTTP, in the test you will be able to put in its place an object that returns a fixed list - no network, no server, no waiting.

The interface keyword in front of class is a modern Dart declaration: it prevents anyone from extending this class instead of implementing it. It is not mandatory, but it makes the intent clear - this type exists to be implemented.

The data: the implementation and its generated providers
// data/product_repository.dart
import 'package:dio/dio.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../domain/product.dart';
import '../domain/product_repository_interface.dart';

part 'product_repository.g.dart';   // without this line, no generation

// @riverpod on a FUNCTION generates a read-only provider.
// The generated name is the function name + "Provider": dioProvider
@riverpod
Dio dio(Ref ref) => Dio(BaseOptions(
      baseUrl: 'https://api.example.com/v1',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 10),
    ));

@riverpod
ProductRepositoryInterface productRepository(Ref ref) =>
    HttpProductRepository(ref.watch(dioProvider));

class HttpProductRepository implements ProductRepositoryInterface {
  HttpProductRepository(this._dio);
  final Dio _dio;

  @override
  Future<List<Product>> fetchProducts() async {
    final r = await _dio.get<List<dynamic>>('/products');
    return (r.data ?? const [])
        .cast<Map<String, dynamic>>()
        .map((j) => Product(
              id: j['id'] as String,
              name: j['name'] as String,
              price: (j['price'] as num).toDouble(),
              inStock: j['inStock'] as bool,
            ))
        .toList();
  }

  @override
  Future<Product> createProduct(Product product) async {
    await _dio.post<void>('/products', data: {'name': product.name});
    return product;
  }
}

The line part 'product_repository.g.dart'; is the one people forget, and the error that follows - "Missing part directive" or a provider that does not exist - is not obvious. The generator writes into that file and the part directive stitches it to yours: without it, the code is generated and never linked.

The naming convention is mechanical and worth learning right away: @riverpod on a function dio generates dioProvider, on a function productRepository it generates productRepositoryProvider. First letter lowercase, plus the suffix. In your code you use the generated name, which your editor does not know until you have run the generator - which is why it pays to keep watch running.

The return type of productRepository is the interface, not HttpProductRepository, and this is a deliberate choice. If you declared the concrete type, the provider could only be replaced with another HttpProductRepository, and the test would lose its foothold.

ref.watch(dioProvider) inside another provider is how dependencies are composed: if one day dioProvider were replaced, productRepositoryProvider would be rebuilt accordingly. It is also what allows you, in a test, to replace only the Dio and leave everything else standing.

AsyncNotifier: state that can be loading

For state that is loaded from outside, @riverpod goes on a class with an asynchronous build method. The state that comes out of it is not a list: it is an AsyncValue, that is "loading", "data" or "error".

presentation/products_list_provider.dart
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../data/product_repository.dart';
import '../domain/product.dart';

part 'products_list_provider.g.dart';

@riverpod
class ProductsList extends _$ProductsList {
  // build() is the first load: the initial state is AsyncLoading
  @override
  Future<List<Product>> build() =>
      ref.read(productRepositoryProvider).fetchProducts();

  Future<void> refresh() async {
    state = const AsyncLoading();
    // guard turns an exception into AsyncError instead of letting it propagate
    state = await AsyncValue.guard(
      () => ref.read(productRepositoryProvider).fetchProducts(),
    );
  }

  Future<void> add(Product nuovo) async {
    final precedente = state.valueOrNull ?? const <Product>[];

    // Optimistic update: show it right away, then confirm
    state = AsyncData([...precedente, nuovo]);

    final esito = await AsyncValue.guard(
      () => ref.read(productRepositoryProvider).createProduct(nuovo),
    );

    // If the server rejected it, roll back
    if (esito is AsyncError) {
      state = AsyncData(precedente);
    }
  }
}

The class extends _$ProductsList, which does not exist in your code: the generator writes it. This is why, as soon as you have written this class, the editor flags an error that goes away only after generation - normal behaviour, not a configuration problem.

AsyncValue.guard is the function worth remembering. It runs the code you pass it and, if it throws an exception, turns it into an AsyncError with the stack trace attached. Without it you would have to write try/catch and build AsyncError(e, st) by hand, and the temptation would be to catch nothing - letting an exception propagate that would bring the widget down instead of showing a message.

In refresh, the line state = const AsyncLoading() before the guard is what makes the loading indicator appear. Remove it and the reload works, but the user sees nothing happen until the new data arrives - and on a slow network will conclude that the button is broken.

The add method shows the optimistic update, which is the main reason you write an AsyncNotifier instead of a read-only provider. The three lines that matter come in this order: I save the previous state, I show the new one immediately, and if the server rejects it I put the previous one back. Without saving it in precedente you would have nothing to go back to, and the item would stay in the list even though it does not exist on the server.

state.valueOrNull ?? const <Product>[] handles the case in which add is called while the state is still loading or in error: in those cases there is no previous list, and state.value would throw an exception. It is the kind of line that looks defensive and instead describes a case that really happens, because the user can press a button before the list has arrived.

The widget: three states, three branches

presentation/products_list_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'products_list_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final prodotti = ref.watch(productsListProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Products'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            // read, not watch: here you need the action, not the value
            onPressed: () =>
                ref.read(productsListProvider.notifier).refresh(),
          ),
        ],
      ),
      body: prodotti.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text('Error: $e')),
        data: (lista) => lista.isEmpty
            ? const Center(child: Text('No products'))
            : ListView.builder(
                itemExtent: 72,
                itemCount: lista.length,
                itemBuilder: (context, i) => ListTile(
                  title: Text(lista[i].name),
                  subtitle: Text('${lista[i].price.toStringAsFixed(2)} EUR'),
                  trailing: Icon(lista[i].inStock
                      ? Icons.check_circle
                      : Icons.remove_circle_outline),
                ),
              ),
      ),
    );
  }
}

ConsumerWidget adds a second parameter to build, the WidgetRef, which is how the widget reaches the providers. You need no widget wrapping the tree other than the ProviderScope at the root of the app.

The distinction between ref.watch and ref.read is the most important one in Riverpod, and here you see both in the same file. watch in the body of build subscribes the widget: when the provider changes, the widget rebuilds. read inside a callback takes the value once and subscribes nothing, and that is correct because onPressed is not evaluated during construction.

Swapping them gives two opposite, characteristic bugs: read in the body of build gives a widget that never updates, watch inside a callback produces a runtime error because there is nothing to subscribe in that context. If you remember only one rule: watch where the value is read, read where an action is called.

prodotti.when(...) forces you to handle all three cases, and this is the reason AsyncValue exists: you cannot forget the error state, because the method does not compile without that branch. The fourth case - data present but an empty list - is not a state of AsyncValue and is handled inside data, where it belongs: "loaded, zero results" is a success, not an error, and showing an endless loading indicator in its place is a classic.

Testing by replacing the repository

Here all the earlier work pays off. You need no dependency container or mock framework with generation: you create a ProviderContainer and declare which provider is to be replaced.

test/products_list_provider_test.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';

// A hand-written double: for two methods you do not need mocktail
class FakeRepository implements ProductRepositoryInterface {
  FakeRepository(this.prodotti, {this.errore});
  final List<Product> prodotti;
  final Object? errore;

  @override
  Future<List<Product>> fetchProducts() async {
    if (errore != null) throw errore!;
    return prodotti;
  }

  @override
  Future<Product> createProduct(Product p) async => p;
}

void main() {
  const unProdotto = Product(id: '1', name: 'Keyboard', price: 49.9, inStock: true);

  test('build exposes the repository list', () async {
    final container = ProviderContainer(
      overrides: [
        productRepositoryProvider.overrideWithValue(
          FakeRepository([unProdotto]),
        ),
      ],
    );
    addTearDown(container.dispose);   // without it, the container stays alive

    final lista = await container.read(productsListProvider.future);

    expect(lista, hasLength(1));
    expect(lista.first.name, 'Keyboard');
  });

  test('a failing repository produces AsyncError', () async {
    final container = ProviderContainer(
      overrides: [
        productRepositoryProvider.overrideWithValue(
          FakeRepository(const [], errore: Exception('network down')),
        ),
      ],
    );
    addTearDown(container.dispose);

    await expectLater(
      container.read(productsListProvider.future),
      throwsA(isA<Exception>()),
    );
  });
}

overrideWithValue on productRepositoryProvider is the central mechanism: the provider under test, productsListProvider, does not know it is in a test and asks for the repository as always. It receives the double. This is why the return type of the provider had to be the interface.

container.read(productsListProvider.future) is the way to wait for the first load: the .future suffix gives the underlying Future, while reading the bare provider would give an AsyncValue that at that instant is still AsyncLoading. Forgetting .future produces a test that checks the loading state and calls it a success.

addTearDown(container.dispose) is not formal cleanup. A ProviderContainer that is not disposed keeps the providers and their listeners alive from one test to the next: the typical symptom is a suite that passes test by test and fails when you run it whole, which is the worst kind of failure to diagnose.

The double is hand-written instead of using mocktail, and for two methods that is the right choice: no stub configuration, and the compiler warns you if the interface changes - which a dynamic mock does not. mocktail pays off when the interface has many methods and in a test you need two of them, or when you have to verify whether a method was called.

The second test deserves a note: with .future, a repository that throws produces a Future that fails, so you check it with throwsA. If instead you wanted to observe the state as the widget sees it, you would read the provider without .future and check that it is an AsyncError - two ways of looking at the same thing, and it pays to know which one you are using.

What you can do now

You can set up generation with the right versions, make a provider depend on an interface so that it can be replaced, handle the three states of AsyncValue without being able to forget one, write an optimistic update that knows how to roll back, and test it all by replacing a provider in a ProviderContainer.

Above all, you know the rule that is got wrong most often: watch where you read a value, read where you invoke an action.

The comparison with the main alternative, and the criteria for choosing, are in Riverpod 3 against BLoC 9; the event and state model of BLoC is developed in events, states and Cubit. On the testing side, ProviderScope with overrides is also used in widget tests, covered in widget testing and golden tests. And since watch decides how often a widget rebuilds, the effect on performance can be measured with the tools described in Impeller, the rendering pipeline and jank.

Sources

  • Riverpod - About code generation - the role of the @riverpod annotation, the part directive and the convention that forms the name of the generated provider. Consulted on 2026-11-08.
  • Riverpod - Providers - difference between function-based and class-based providers, and the semantics of ref.watch versus ref.read. Consulted on 2026-11-08.
  • Riverpod - Testing - ProviderContainer, the overrides, the need to dispose the container and the use of .future to wait for the first load. Consulted on 2026-11-08.
  • Riverpod - Migration to 3.0 - useful to understand which names changed compared with the older material still in circulation. Consulted on 2026-11-08.
  • pub.dev - flutter_riverpod and riverpod_generator - the pages from which the current versions are read. Consulted on 2026-11-08.
  • Version measurement - every number in the pubspec comes from https://pub.dev/api/packages/<name>, field latest.version, queried on 2026-11-08: flutter_riverpod 3.5.0, riverpod_annotation 4.0.8, riverpod_generator 4.0.10, riverpod_lint 3.2.0, build_runner 2.17.1, mocktail 1.0.5, freezed 4.0.3.
  • Command check - that flutter pub run forwards to dart pub run was verified by running flutter pub run without arguments on Flutter 3.44.2: the usage printed is dart pub run. The Dart code of the examples was not compiled.

The first five entries are project documentation, and for Riverpod they count more than usual: the structure of the documents changed between version 2 and version 3, so many links you find online lead to pages that no longer exist. The last two separate what is measured - the versions, the behaviour of the command - from what is only read, that is the behaviour of the code. It is the distinction that lets you trust the numbers without trusting everything.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects