Back to Blog

Riverpod + Freezed + build_runner: My Flutter State Management Setup

Dev Notes · Published November 17, 2026

Every Flutter app I ship uses the same three tools for state and data: Riverpod for state and dependency injection, Freezed for immutable models, and build_runner to generate the boilerplate for both. This post shows the setup as I run it in production, using real patterns from Sundry, a bookkeeping app with about 650 Dart files and 25 features.

If you want the folder structure around this code, read the companion post: how I structure a Flutter app.

Why these three together

  • Riverpod holds async state, caches it, rebuilds only what changed, and replaces get_it or InheritedWidget for dependency injection. Every provider can be overridden in tests.
  • Freezed gives you immutable data classes with copyWith, value equality, toString, JSON and sealed unions without writing any of it by hand.
  • build_runner runs both generators (plus json_serializable) so the code you write stays short.

The result: a model is about 15 lines, a provider is a function or a small class, and the compiler catches most mistakes.

The packages

dependencies:
  hooks_riverpod: ^3.3.1
  flutter_hooks: ^0.21.3
  riverpod_annotation: ^4.0.2
  freezed_annotation: ^3.1.0
  json_annotation: ^4.11.0

dev_dependencies:
  build_runner: ^2.15.0
  riverpod_generator: ^4.0.3
  freezed: ^3.2.5
  json_serializable: ^6.13.0

I use hooks_riverpod instead of flutter_riverpod because I like flutter_hooks for local widget state (text controllers, loading flags). If you don’t use hooks, swap in flutter_riverpod and nothing else in this post changes. More on hooks in Flutter Hooks with Riverpod.

1. A Freezed model

import 'package:freezed_annotation/freezed_annotation.dart';

part 'client.freezed.dart';
part 'client.g.dart';

@freezed
abstract class Client with _$Client {
  const factory Client({
    required String id,
    required String businessId,
    required String name,
    String? email,
    String? phone,
    required DateTime createdAt,
  }) = _Client;

  factory Client.fromJson(Map<String, dynamic> json) => _$ClientFromJson(json);
}

Things to notice:

  • abstract class is required in Freezed 3. Use sealed class when you have several constructors (a union type).
  • Two part lines: .freezed.dart for the class, .g.dart for JSON. Forget one and the build fails with a confusing “undefined name” error.
  • You get copyWith, ==, hashCode and toString for free: client.copyWith(name: 'Acme Inc.').

Map snake_case columns once, in build.yaml

My backend is Postgres, so columns are business_id and created_at. Instead of putting @JsonKey(name: ...) on every field, I set it once for the whole project:

# build.yaml
targets:
  $default:
    builders:
      json_serializable:
        options:
          field_rename: snake
          explicit_to_json: true

Now Client.fromJson(row) reads a database row directly. No hand-written mappers in the repository.

2. A Result type for errors

I don’t let exceptions travel from the data layer into providers and widgets. Repositories return a Result<T>, which is also a Freezed sealed class:

@freezed
sealed class Result<T> with _$Result<T> {
  factory Result.value(T value) = ResultValue<T>;
  factory Result.failed(Object error, StackTrace stackTrace) = ResultFailed<T>;

  /// Runs [body] and captures success or failure.
  static Future<Result<T>> guard<T>(Future<T> Function() body) async {
    try {
      return Result<T>.value(await body());
    } catch (e, st) {
      return Result<T>.failed(e, st);
    }
  }
}

Because it’s sealed, a Dart 3 switch over it must handle both cases or it won’t compile. The try/catch lives in exactly one place.

3. The repository

The domain layer defines the interface:

abstract interface class ClientRepository {
  Future<Result<List<Client>>> list();
  Future<Result<Client>> create(ClientDraft draft);
  Future<Result<void>> delete(String id);
}

The data layer implements it. Every method is wrapped in Result.guard:

class SupabaseClientRepository implements ClientRepository {
  SupabaseClientRepository(this._db, this._businessId);

  final SupabaseClient _db;
  final String _businessId;

  @override
  Future<Result<List<Client>>> list() => Result.guard(() async {
        final rows = await _db
            .from('clients')
            .select()
            .eq('business_id', _businessId)
            .order('name');
        return rows.map(Client.fromJson).toList();
      });

  // create / delete follow the same shape
}

4. Generated providers

With riverpod_generator, a provider is an annotated function or class. The generator picks the provider type from what you return.

The repository is a plain function provider. It’s also where dependency injection happens:

part 'client_providers.g.dart';

@riverpod
ClientRepository clientRepository(Ref ref) {
  final business = ref.watch(activeBusinessProvider);
  return SupabaseClientRepository(ref.watch(supabaseProvider), business.id);
}

When the user switches business, activeBusinessProvider changes, the repository is rebuilt, and everything that watches it reloads. I don’t write any of that wiring by hand.

The list of clients is a class-based async notifier: it loads data in build and has methods that change it.

@riverpod
class Clients extends _$Clients {
  @override
  Future<List<Client>> build() async {
    final result = await ref.watch(clientRepositoryProvider).list();
    return switch (result) {
      ResultValue(:final value) => value,
      ResultFailed(:final error, :final stackTrace) =>
        Error.throwWithStackTrace(error, stackTrace),
    };
  }

  Future<Result<Client>> createClient(ClientDraft draft) async {
    final result = await ref.read(clientRepositoryProvider).create(draft);
    if (result case ResultValue(:final value)) {
      state = AsyncData([...?state.value, value]);
    }
    return result;
  }
}

Two decisions here that I make the same way everywhere:

  • build throws on failure so Riverpod turns it into AsyncError, and the screen shows an error state.
  • Mutations return the Result instead of throwing, so the screen that triggered the save decides what to show (a snackbar, an inline message). On success I update state locally instead of reloading the whole list.

Providers are auto-dispose by default with the generator. Use @Riverpod(keepAlive: true) for things that should live for the whole session, such as the signed-in user or the active business.

Family providers are just arguments

@riverpod
Future<Client> client(Ref ref, String id) async { ... }

// usage
ref.watch(clientProvider('c_123'));

No .family modifier and no records to pack parameters into.

5. Using it in the UI

Watching an async provider gives an AsyncValue. I use a Dart 3 switch on it:

class ClientsScreen extends HookConsumerWidget {
  const ClientsScreen({super.key});

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

    return switch (clients) {
      AsyncData(:final value) when value.isEmpty => const EmptyState(),
      AsyncData(:final value) => ClientList(clients: value),
      AsyncError(:final error) => ErrorState(error: error),
      _ => const Center(child: CircularProgressIndicator()),
    };
  }
}

For a form, hooks hold the local state and the notifier does the work:

final name = useTextEditingController();
final saving = useState(false);

Future<void> save() async {
  saving.value = true;
  final result = await ref
      .read(clientsProvider.notifier)
      .createClient(ClientDraft(name: name.text.trim()));
  if (!context.mounted) return;
  saving.value = false;
  switch (result) {
    case ResultValue(:final value):
      context.go('/clients/${value.id}');
    case ResultFailed(:final error):
      showError(context, error);
  }
}

The rule: ref.watch in build, ref.read in callbacks. Watching inside a button handler is the most common Riverpod bug I see when taking over an existing app. To make screens rebuild less, see Provider Selector and Riverpod select.

6. Testing

Every provider can be replaced, so tests don’t need a backend. I use mocktail for the repository:

class _MockRepo extends Mock implements ClientRepository {}

void main() {
  test('createClient adds the new client to the list', () async {
    final repo = _MockRepo();
    when(() => repo.list()).thenAnswer((_) async => Result.value([]));
    when(() => repo.create(any())).thenAnswer(
      (_) async => Result.value(testClient(name: 'Acme')),
    );

    final container = ProviderContainer.test(
      overrides: [clientRepositoryProvider.overrideWith((ref) => repo)],
    );

    await container.read(clientsProvider.future);
    await container.read(clientsProvider.notifier).createClient(
          const ClientDraft(name: 'Acme'),
        );

    expect(container.read(clientsProvider).value!.single.name, 'Acme');
  });
}

ProviderContainer.test disposes the container when the test ends. Freezed’s value equality means expect(a, b) compares models field by field.

7. Running build_runner

dart run build_runner watch

Keep watch running in a terminal while you work. Use build once in CI or after pulling changes:

dart run build_runner build

Run it after changing any @freezed class, any @JsonSerializable model, or any @riverpod provider.

My project setup around it:

  • Hide generated files from the analyzer so warnings in generated code don’t drown yours:

    # analysis_options.yaml
    analyzer:
      exclude:
        - "**/*.g.dart"
        - "**/*.freezed.dart"
    plugins:
      riverpod_lint: 3.1.3
  • riverpod_lint catches mistakes such as watching a provider in a callback or a missing dependency. It runs through the analyzer plugin system, so warnings show in your editor.

  • Gitignore generated files (*.g.dart, *.freezed.dart). Reviews stay clean. The cost: CI and every fresh clone must run build_runner build before flutter analyze or flutter test.

Pitfalls I hit often

  1. Missing part line. The error mentions _$Client being undefined. Check the part file name matches the source file exactly.
  2. Forgetting abstract/sealed on a Freezed 3 class after upgrading from Freezed 2.
  3. A provider that “forgets” its data. Generated providers auto-dispose when nothing watches them. Make it keepAlive: true, or watch it from somewhere that stays mounted.
  4. Stale generated code. If an error makes no sense, stop watch, run build once, and restart the analyzer.
  5. Reading state.value during loading. It’s null while the first load runs. Use ...?state.value (as above) when you append.

When I’d skip some of this

For a small app with three screens, Riverpod without generation is fine, and plain classes with a hand-written copyWith are fine too. The setup pays off once you have many models, async data from a backend, and screens that depend on each other. That covers most apps that make money.

Want help setting this up in your app, or untangling one that grew without a structure? Get in touch.