Flutter clean architecture with Riverpod, without ceremony
A Flutter clean architecture that survives year two: feature-first folders, entities vs DTOs, repository interfaces, Riverpod 3 AsyncNotifier, sealed Failure.
On this page
By year two, the usual problem in a clean-architecture Flutter project is ceremony: use cases that forward one call, interfaces nobody fakes, mappers for mappers. I keep three thin layers per feature (domain, data, presentation), wire every dependency in Riverpod providers and nowhere else, and make each extra abstraction justify itself. The examples use a listings feature and Riverpod 3.
Feature-first folders, layers inside
lib/
core/
error/failure.dart # sealed Failure
network/dio_provider.dart
network/guard.dart # DioException -> Failure
providers.dart # storage, clock, analytics
design_system/ # shared widgets and tokens
features/
listings/
domain/
listing.dart # entity
listings_repository.dart # abstract interface
publish_listing.dart # use case, because it earns it
data/
listing_dto.dart
listings_api.dart
listings_repository_impl.dart
presentation/
my_listings_controller.dart # AsyncNotifier
my_listings_page.dart
widgets/
listings_providers.dart # composition root for the feature
auth/
app.dart
main.dart
test/ # mirrors lib/I group by feature rather than by layer (lib/domain, lib/data and lib/presentation at the top) because work arrives one feature at a time. A pull request for listings touches one folder, and deleting a feature means deleting that folder. Ownership is obvious as well.
Inside each feature there is one dependency rule: presentation and data depend on domain, and domain depends on nothing. So no Flutter, no Dio and no JSON in domain/. Features never import each other's data/ or presentation/. When two features need the same entity, it moves to a shared place. The domain rule is cheap to enforce: a one-line CI step greps lib/features/*/domain for package:flutter and package:dio and fails if it finds anything.
Entities for the app, DTOs for the API
The entity describes what the app means. The DTO mirrors what the API sends.
// domain/listing.dart: plain Dart, no Flutter, no JSON
enum ListingStatus { draft, published, archived }
class Listing {
const Listing({required this.id, required this.title, required this.status});
final String id;
final String title;
final ListingStatus status;
bool get canPublish => status == ListingStatus.draft && title.isNotEmpty;
}
// data/listing_dto.dart: mirrors the API, tolerant of its quirks
class ListingDto {
ListingDto.fromJson(Map<String, dynamic> json)
: id = json['id'] as String,
title = json['title'] as String?,
status = json['status'] as String?;
final String id;
final String? title;
final String? status;
Listing toEntity() => Listing(
id: id,
title: title ?? '',
status: ListingStatus.values.asNameMap()[status] ?? ListingStatus.draft,
);
}toEntity() is the one place that absorbs backend quirks, such as a renamed field, a missing title or a status value added by a newer backend. I decide per field. An unknown status can fall back safely. A missing id cannot, so it is cast strictly and fails loudly. Business rules such as canPublish live on the entity so they don't end up duplicated in widgets.
The trade-off is one extra class per model. I accept it for anything shown on screen or sent back to the API. For a read-only config payload consumed in one place, a single class is fine. Generating fromJson with a code generator is fine too. The split is the part I care about.
Repositories throw a sealed Failure
The repository interface lives in domain and speaks the feature's language. The implementation lives in data, and every method goes through one guard function that turns infrastructure exceptions into a sealed Failure.
// domain/listings_repository.dart
abstract interface class ListingsRepository {
Future<List<Listing>> fetchMine({required int page});
Future<Listing> publish(String id);
}
// core/error/failure.dart
sealed class Failure implements Exception { const Failure(); }
final class NetworkFailure extends Failure { const NetworkFailure(); }
final class AuthFailure extends Failure { const AuthFailure(); }
final class ServerFailure extends Failure { const ServerFailure(); }
final class UnexpectedFailure extends Failure {
const UnexpectedFailure(this.cause);
final Object cause;
}
// core/network/guard.dart: the only code that knows Dio's error types
Future<T> guard<T>(Future<T> Function() call) async {
try {
return await call();
} on DioException catch (e) {
throw switch (e.type) {
DioExceptionType.connectionError ||
DioExceptionType.connectionTimeout ||
DioExceptionType.sendTimeout ||
DioExceptionType.receiveTimeout => const NetworkFailure(),
_ when e.response?.statusCode == 401 => const AuthFailure(),
_ => const ServerFailure(),
};
} on Failure {
rethrow;
} catch (e) {
throw UnexpectedFailure(e); // a bug: record it as a non-fatal here
}
}Implementation methods become one-liners: guard(() async => (await _api.publish(id)).toEntity()). A parsing error from a strict cast lands in UnexpectedFailure, which is exactly where I want crash reporting to look.
I throw from repositories instead of returning an Either or Result, because AsyncNotifier and AsyncValue already model data, loading and error. Wrapping results in another type means unwrapping twice in every notifier. So repositories throw typed failures and AsyncValue carries them. If your team already uses a functional library everywhere, stay with it. Mixing the two styles is worse than either one.
Use cases only when they earn their place
I write a use case when the logic coordinates more than one repository or service, when it holds a business rule that must behave the same on every screen, or when it deserves tests of its own. One of those is enough.
PublishListing passes. It checks listing.canPublish, uploads compressed photos through a MediaRepository, publishes through ListingsRepository, then logs an analytics event. A GetMyListings class that only forwards repository.fetchMine() does not, so the notifier calls the repository directly. If a forwarding call later grows a rule, extracting a use case takes a few minutes. Deleting fifty pass-through classes is a migration nobody ever schedules.
A use case is a plain class with a call method, exposed through its own Provider like every other dependency.
Riverpod providers as the composition root
Each feature wires itself in one file, and repository providers are typed as the interface:
// features/listings/listings_providers.dart
final listingsApiProvider =
Provider<ListingsApi>((ref) => ListingsApi(ref.watch(dioProvider)));
final listingsRepositoryProvider = Provider<ListingsRepository>(
(ref) => ListingsRepositoryImpl(ref.watch(listingsApiProvider)),
);
final myListingsProvider = AsyncNotifierProvider.autoDispose<
MyListingsController, List<Listing>>(MyListingsController.new);
// test/features/listings/my_listings_controller_test.dart
class OfflineListingsRepository implements ListingsRepository {
@override
Future<List<Listing>> fetchMine({required int page}) async =>
throw const NetworkFailure();
@override
Future<Listing> publish(String id) async => throw const NetworkFailure();
}
void main() {
test('exposes a NetworkFailure when offline', () async {
final container = ProviderContainer.test(
retry: (_, _) => null, // the first failure, not the tenth
overrides: [
listingsRepositoryProvider.overrideWithValue(OfflineListingsRepository()),
],
);
final sub = container.listen(myListingsProvider.future, (_, _) {});
await expectLater(sub.read(), throwsA(isA<NetworkFailure>()));
});
}The test container turns automatic retry off. Riverpod 3 retries a provider whose build throws an exception, up to ten times with a growing delay, and provider.future keeps waiting until the retries are spent. That suits a NetworkFailure in the app. In a test it only hides the first failure behind a timeout. In the app, the same callback is where to say which failures deserve a second try:
ProviderScope(
retry: (retryCount, error) => error is NetworkFailure && retryCount < 3
? Duration(milliseconds: 400 * (retryCount + 1))
: null, // an AuthFailure will not fix itself
child: const App(),
)A few rules keep the graph readable:
- Infrastructure providers (Dio, secure storage, clock, analytics) live in
core/, and features never construct them. - Typing the provider as
Provider<ListingsRepository>hides implementation-only methods from consumers, and an override is one line. - Notifiers get dependencies from
ref:ref.watchinbuild,ref.readin methods. - I override at the boundary under test: the repository for controller tests,
dioProviderwith a fake HTTP adapter for repository tests, environment providers inmainfor flavors. - One DI mechanism. A service locator next to Riverpod means two graphs and two lifecycles to reason about.
AsyncNotifier for screen state
class MyListingsController extends AsyncNotifier<List<Listing>> {
@override
Future<List<Listing>> build() =>
ref.watch(listingsRepositoryProvider).fetchMine(page: 1);
// Failures propagate to the caller, which shows a snackbar.
Future<void> publish(String id) async {
final published = await ref.read(listingsRepositoryProvider).publish(id);
if (!ref.mounted) return; // the screen was left while this was in flight
final current = state.value ?? const <Listing>[];
state = AsyncData([for (final l in current) l.id == id ? published : l]);
}
}
class MyListingsPage extends ConsumerWidget {
const MyListingsPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return ref.watch(myListingsProvider).when(
loading: () => const ListingsSkeleton(),
error: (e, _) => ErrorView(
message: messageFor(e is Failure ? e : UnexpectedFailure(e))),
data: (items) => RefreshIndicator(
onRefresh: () => ref.refresh(myListingsProvider.future),
child: ListingsList(items: items),
),
);
}
}
String messageFor(Failure failure) => switch (failure) {
NetworkFailure() => 'You are offline. Pull to retry.',
AuthFailure() => 'Your session has expired.',
ServerFailure() || UnexpectedFailure() => 'Something went wrong.',
};build() loads the first state, and AsyncValue gives the UI its loading, data and error states without hand-written flags. A skeleton covers the first load. During pull-to-refresh, when keeps the current list on screen by default. A failed publish throws to the caller instead of replacing the whole list with an error screen. Because Failure is sealed, messageFor has no default branch: add a new subtype and the build breaks at every place that renders errors, which is the point. In a real app those strings come from localization files.
Screen controllers are autoDispose, so leaving the screen frees the state. That is also why publish checks ref.mounted after its await: if the user left the screen meanwhile, the provider is gone, and Riverpod 3 throws when a disposed notifier touches its state. Session and settings providers are not autoDispose. For paginated lists, I keep items, next page and a loading-more flag in one state object rather than one provider per page (the full notifier is in the article on long lists). Side effects such as navigation and snackbars go through ref.listen in the widget, never inside the notifier.
Write down when to add an abstraction
Year two is also when people who weren't around for the original decisions join the project, so the rules for adding an abstraction need to be written down:
| Abstraction | Add it when | Skip it when |
|---|---|---|
| Use case | It coordinates several dependencies or holds a shared rule | It forwards one call |
| Repository interface | Data comes from outside the app | The data is local and has one source |
| Separate DTO | The model is shown on screen or sent back | A read-only payload used once |
New Failure subtype | The UI must react differently | Only the log message differs |
A few more habits:
- Code moves to
core/on its second real use, not in anticipation of one. - No base classes for notifiers or repositories.
guardis a function, and composition beats inheritance here. - A feature template (empty folders and a providers file) means a new feature starts with the right shape at no cost.
- The dependency rule and the table above fit on one page. That page saves more review comments than any lint.
Why an 80% coverage gate holds up
On my current project we enforce an 80% coverage gate in GitLab CI. The layering is what makes a gate like that sustainable: entities, guard and notifiers are tested with plain Dart tests and fakes, and widget tests stay focused on the screens with real logic.