Riverpod + Freezed + build_runner: My Flutter State Management Setup
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 classis required in Freezed 3. Usesealed classwhen you have several constructors (a union type).- Two
partlines:.freezed.dartfor the class,.g.dartfor JSON. Forget one and the build fails with a confusing “undefined name” error. - You get
copyWith,==,hashCodeandtoStringfor 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:
buildthrows on failure so Riverpod turns it intoAsyncError, and the screen shows an error state.- Mutations return the
Resultinstead of throwing, so the screen that triggered the save decides what to show (a snackbar, an inline message). On success I updatestatelocally 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_lintcatches 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 runbuild_runner buildbeforeflutter analyzeorflutter test.
Pitfalls I hit often
- Missing
partline. The error mentions_$Clientbeing undefined. Check thepartfile name matches the source file exactly. - Forgetting
abstract/sealedon a Freezed 3 class after upgrading from Freezed 2. - 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. - Stale generated code. If an error makes no sense, stop
watch, runbuildonce, and restart the analyzer. - Reading
state.valueduring loading. It’snullwhile 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.