Organizing by feature and separating three layers: when it is really needed
Organize folders by feature (products/, cart/, auth/) and,
inside each one, separate the domain (rules and contracts), the data (network, cache,
JSON) and the presentation (screens and state). The concrete gain is only one: whoever touches the cart
works in one folder, and the rule "the domain imports nothing from the other layers" can be checked with
a script, as we will do. It is not, however, the mandatory structure: the
official architecture guide recommends two
layers (UI and data) and treats the domain as optional; the
recommendations page writes that you need it "only if
your app has exceptionally complex logic that crowds the ViewModels, or if you find yourself repeating logic",
and that in most apps use cases "add unnecessary overhead".
So the criterion is: start with two layers; introduce the domain when a business rule shows up in two screens. The examples below include the domain because it is the purpose of the article, but the rule to take away is this one. The previous chapter on integration testing showed why an orderly structure helps tests; the comparison between state managers is in Riverpod versus BLoC, and how to use BLoC in the presentation layer is in BLoC in depth.
All the code below is pure Dart with the riverpod 3.5.0 package, compiled and run with
Dart 3.12.2 on 2026-11-12: the presentation part that draws widgets is not there, because it is the least
interesting for architecture and depends on Flutter.
The structure, by feature
The comparison with organizing "by type" (models/, repositories/, screens/)
is in the cost of change. To add a feature in a by-type structure you touch all the
folders; in a by-feature one you touch one. The price is uncertainty about where to put shared
code (a component used by two features): the useful rule is to put it in a common folder
only on the second occurrence, not the first. This is the structure of the example, produced by the command:
find lib/features -name '*.dart' | sort
// Output:
// lib/features/products/data/product_dto.dart
// lib/features/products/data/products_repository_impl.dart
// lib/features/products/domain/get_products.dart
// lib/features/products/domain/product.dart
// lib/features/products/domain/products_repository.dart
// lib/features/products/presentation/products_provider.dart
Six files, three layers. Notice what is missing: there are no entities/ or usecases/ folders with
a single file inside. A subfolder is created when it holds more than one item, otherwise it is
ceremony. Let us move on to the layers, from the centre outwards.
Domain: types and rules without dependencies
The domain contains the entity, the repository contract and a use case. The amount is an integer in
cents, because with binary decimals sums of prices may not add up, and a monetary error is the
kind of defect you discover late. The ProductsRepository contract is an
abstract interface class, and the ProductsUnavailable error belongs to the domain: whoever
receives it must not need to know whether the cause is HTTP or a corrupted file.
/// Domain entity: pure Dart, amount in cents.
class Product {
const Product({required this.id, required this.name, required this.priceCents});
final String id;
final String name;
final int priceCents;
@override
bool operator ==(Object other) => other is Product && other.id == id;
@override
int get hashCode => id.hashCode;
}
The entity has equality based only on the id: two products with the same identifier are the
same product even if the price has changed. It is a domain choice, useful for replacing an entry in a
list, and it must be made consciously because it changes how widgets decide whether to rebuild.
import 'product.dart';
/// The domain declares the contract; it does not know who implements it.
abstract interface class ProductsRepository {
Future<List<Product>> getProducts({String? category});
}
/// Domain error: the upper layer knows neither HTTP nor JSON.
class ProductsUnavailable implements Exception {
const ProductsUnavailable(this.cause);
final Object cause;
@override
String toString() => 'ProductsUnavailable($cause)';
}
The contract says what is needed (a list of products, possibly by category) and not how to obtain it. This is what lets you replace the network in tests and change data provider without touching the screens: the only thing the upper layers know is this interface.
import 'product.dart';
import 'products_repository.dart';
/// A use case: sorts by price, a business rule that is neither UI nor network.
class GetProducts {
const GetProducts(this._repository);
final ProductsRepository _repository;
Future<List<Product>> call({String? category}) async {
final products = await _repository.getProducts(category: category);
return [...products]..sort((a, b) => a.priceCents.compareTo(b.priceCents));
}
}
The rule in the use case is small but real: it returns a sorted copy ([...products]..sort)
instead of sorting the list it received, because modifying the argument that comes from the repository would be a
side effect on someone else's data. If all a use case does is forward the call to the
repository, as in many examples, it is not needed: the screen can call the repository directly.
Data: JSON, network and local copy
The DTO describes the shape of the server's JSON and knows how to convert itself into an entity: the dependency goes from data to the
domain, never the other way round. Here the server sends prices in euros as numbers, and the conversion to cents
with round() avoids decimal imprecision: in Dart 1.15 * 100 is 114.99999999999999 (measured), and a simple truncation would give 114 cents instead of 115. The cast
(x as num).toDouble() is deliberate: JSON does not distinguish integers from decimals, and a price "5" arrives
as an integer.
import '../domain/product.dart';
/// Shape of the server's JSON; it knows how to convert itself into an entity, the domain does not.
class ProductDto {
const ProductDto({required this.id, required this.name, required this.price});
factory ProductDto.fromJson(Map<String, Object?> json) => ProductDto(
id: json['id']! as String,
name: json['name']! as String,
price: (json['price']! as num).toDouble(), // the server sends euros
);
final String id;
final String name;
final double price;
Product toEntity() =>
Product(id: id, name: name, priceCents: (price * 100).round());
}
The repository uses the DTO to turn each JSON element into an entity. If a field is missing or has the wrong
type, fromJson throws an error at the data boundary and not inside the logic: that is the right
place to notice it.
import '../domain/product.dart';
import '../domain/products_repository.dart';
import 'product_dto.dart';
typedef RemoteFetch = Future<List<Map<String, Object?>>> Function(String? category);
class ProductsRepositoryImpl implements ProductsRepository {
ProductsRepositoryImpl({required RemoteFetch remote}) : _remote = remote;
final RemoteFetch _remote;
final Map<String?, List<Product>> _cache = {};
/// Network first; if it fails and there is a copy, serve that.
@override
Future<List<Product>> getProducts({String? category}) async {
try {
final json = await _remote(category);
final products = json.map(ProductDto.fromJson).map((d) => d.toEntity()).toList();
_cache[category] = products;
return products;
} catch (error) {
final cached = _cache[category];
if (cached != null) return cached;
throw ProductsUnavailable(error);
}
}
}
The cache strategy is a choice, and it must be declared: first the network is tried, and only if it fails is the
copy served. The "cache first" alternative is faster but shows stale data forever if nobody clears it;
many examples write it without noticing the defect. Note also what the catch block does:
if there is no copy, it converts any error into ProductsUnavailable, so the layers above
handle a single type. The flip side is that a programming error (a wrong cast) becomes "not
available" and risks being hidden: in production log the original cause before converting it.
Presentation: the only place where the implementation is chosen
Riverpod providers connect the layers: each declares what it depends on with ref.watch, and
Riverpod builds the graph when needed. The concrete repository implementation is chosen in a
single place, productsRepositoryProvider, and the network is exposed as a provider of its own,
remoteFetchProvider, precisely so it can be replaced. From a test's point of view, this is the
only point to touch.
import 'package:riverpod/riverpod.dart';
import '../data/products_repository_impl.dart';
import '../domain/get_products.dart';
import '../domain/product.dart';
import '../domain/products_repository.dart';
/// The only place where the concrete implementation is chosen.
final remoteFetchProvider = Provider<RemoteFetch>(
(ref) => (category) async => throw UnimplementedError('connect the HTTP client'),
);
final productsRepositoryProvider = Provider<ProductsRepository>(
(ref) => ProductsRepositoryImpl(remote: ref.watch(remoteFetchProvider)),
);
final getProductsProvider = Provider<GetProducts>(
(ref) => GetProducts(ref.watch(productsRepositoryProvider)),
);
final productsProvider = FutureProvider.family<List<Product>, String?>(
(ref, category) => ref.watch(getProductsProvider)(category: category),
);
To see the result I wrote a program that replaces only the network with a fake function:
the rest (repository, use case, providers) is the real code. It is the shape of a widget test with
ProviderScope(overrides: ...), without the widget.
import 'package:riverpod/riverpod.dart';
import 'features/products/domain/products_repository.dart';
import 'features/products/presentation/products_provider.dart';
Future<void> main() async {
var online = true;
final container = ProviderContainer(
overrides: [
// In the "test" only the outer end is replaced: the network.
remoteFetchProvider.overrideWithValue((category) async {
if (!online) throw Exception('network down');
return [
{'id': 'b', 'name': 'Notebook', 'price': 4.8},
{'id': 'a', 'name': 'Pen', 'price': 2.5},
];
}),
],
);
final first = await container.read(productsProvider(null).future);
print('with network: ${first.map((p) => '${p.name} ${p.priceCents}c').join(', ')}');
online = false;
container.invalidate(productsProvider(null));
final second = await container.read(productsProvider(null).future);
print('without network: ${second.length} products from the copy');
// Without a copy the error must come out right away: Riverpod 3's automatic retry is switched off.
final empty = ProviderContainer(retry: (_, _) => null, overrides: [
remoteFetchProvider.overrideWithValue((c) async => throw Exception('network down')),
]);
try {
await empty.read(productsProvider('books').future);
} on ProductsUnavailable catch (e) {
print('without network and without a copy: ${e.runtimeType}');
}
container.dispose();
empty.dispose();
}
// Output:
// with network: Pen 250c, Notebook 480c
// without network: 2 products from the copy
// without network and without a copy: ProductsUnavailable
The output shows the logic of the three layers working together: with the network the products arrive sorted by
price (the 250-cent pen before the 480-cent notebook), even though the server sent them in the opposite
order; without the network the repeated request is served from the copy; without network and without a copy the error that comes out
is ProductsUnavailable and not the raw exception. Note that the third scenario uses the category
"books": the cache is per category, and that one was never loaded. Note also the line retry: (_, _) => null:
Riverpod 3 retries providers that fail, and without that line my first run stopped after the first two lines
and printed nothing for the third scenario, because the wait never reached the error.
Enforcing the rule with a script
"The domain depends on nobody" is a rule that gets lost silently: one convenient import is enough, and six
months later the domain knows HTTP. It can be checked. The following program walks the files of the
feature and flags forbidden imports; I ran it on the code as it is and after deliberately adding an
import from ../data in product.dart.
import 'dart:io';
/// Rule: domain does not import data, presentation or Flutter;
/// data does not import presentation.
const forbidden = {
'domain': ['/data/', '/presentation/', 'package:flutter', '../data', '../presentation'],
'data': ['/presentation/', '../presentation'],
};
void main(List<String> args) {
final root = Directory(args.isEmpty ? 'lib/features' : args.first);
var violations = 0;
for (final file in root.listSync(recursive: true).whereType<File>()) {
if (!file.path.endsWith('.dart')) continue;
final parts = file.path.split('/');
final layer = parts.firstWhere(forbidden.containsKey, orElse: () => '');
if (layer.isEmpty) continue;
for (final (i, line) in file.readAsLinesSync().indexed) {
if (!line.startsWith('import ')) continue;
for (final bad in forbidden[layer]!) {
if (line.contains(bad)) {
violations++;
print('${file.path}:${i + 1}: $layer cannot import "$bad"');
break; // one report per line
}
}
}
}
print(violations == 0 ? 'layers respected' : '$violations violations');
exit(violations == 0 ? 0 : 1); // the value returned by main() would be ignored
}
// Output:
// -- code as it is:
// layers respected
// exit=0
// -- after adding an import from ../data in product.dart:
// lib/features/products/domain/product.dart:1: domain cannot import "/data/"
// 1 violations
// exit=1
In the output the second case ends with code 1, which makes a pipeline fail. A detail I
discovered while writing it: in Dart the value returned by main() is ignored, so to get
a non-zero exit code you must call exit(1); the first version of the script,
which returned 1, ended with 0. The check is deliberately crude (it looks for text in the
import lines): for large projects more precise analyzers exist, but a thirty-line script
already catches the case that matters.
When to extract a feature into a package
Extract a feature into a separate package when two apps share it or when you want the
compiler to prevent forbidden imports: in a package, what is not in the dependencies cannot be
imported. With the by-feature structure the move is mechanical but not free: you need a
pubspec.yaml per package and version management. Before getting there, the script from the last
section gives almost the same advantage without that cost.
What you can do now
You can choose between two and three layers according to the problem, design a feature with domain, data and presentation, replace only the network in a test, and make CI fail when someone violates the direction of dependencies. To see how the framework builds what your presentation will show go to Flutter Internals; to test the layers with widgets and goldens go to Widget testing.
Sources
- Guide to app architecture - two layers (UI and data), components and MVVM, accessed 2026-11-12
- Architecture recommendations - the domain as a conditional layer and use cases, accessed 2026-11-12
- Provider vs Riverpod - providers are plain Dart objects, usable even without Flutter, accessed 2026-11-12
- What's new in Riverpod 3.0 - testing utilities and overrides, accessed 2026-11-12
- Class modifiers -
interface classandabstract interface class, accessed 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment