cat blog/la-clean-architecture-avec-flutter-decouper-par-fonctionnalite-et-par-couche.md
Clean Architecture with Flutter: splitting by feature and by layer
Solution Architect


Contents
In the previous article, SOLID principles in practice, we ended on dependency inversion: business logic depends on abstractions, and the tools adapt to them. Taken all the way, that idea gives a whole architecture, described by Robert C. Martin as Clean Architecture.
I apply it mostly in Flutter, because that's where the problem hurts most. A mobile app often starts with screens that call the API directly, parse JSON and handle errors in the widget. That works for three screens. By the twentieth, every screen has reinvented its loading handling, nothing is testable without a network, and going offline means redoing everything.
This article shows how I split a Flutter app by feature, then by layer, on a simple example: displaying a user's orders.
Three layers, one rule
Each feature is split into three layers. The whole architecture rests on one rule: dependencies point toward the domain, never the other way.


The domain knows nothing about Flutter, the API or the local database. The data layer implements the contracts it defines: that's the dependency inversion from the previous article, applied to the whole app. Result: you can change APIs, add a cache or rewrite the UI without touching business rules.
The domain: the core, with no dependencies
The domain/ folder contains only pure Dart: no Flutter, http or database imports. It describes what the app does, not how.
The entity, a simple, immutable business object:
// lib/features/orders/domain/entities/order.dart
class Order {
const Order({
required this.id,
required this.reference,
required this.total,
required this.status,
});
final String id;
final String reference;
final int total; // in CFA francs
final OrderStatus status;
}The repository contract, which the data layer must honor:
// lib/features/orders/domain/repositories/order_repository.dart
abstract interface class OrderRepository {
Future<List<Order>> getOrders();
}The use case, which carries a business rule. Here, show only non-cancelled orders:
// lib/features/orders/domain/usecases/get_active_orders.dart
class GetActiveOrders {
const GetActiveOrders(this._repository);
final OrderRepository _repository;
Future<List<Order>> call() async {
final orders = await _repository.getOrders();
return orders.where((o) => o.status != OrderStatus.cancelled).toList();
}
}Some use cases only forward the call to the repository. I only create them when a business rule exists: otherwise, the state calls the repository directly.
The data layer: talking to the outside world
The data/ folder knows where data comes from. It contains three kinds of classes.
The model, which knows the API's JSON format and converts it to an entity:
// lib/features/orders/data/models/order_model.dart
class OrderModel {
const OrderModel({required this.id, required this.reference, required this.total, required this.status});
factory OrderModel.fromJson(Map<String, dynamic> json) => OrderModel(
id: json['id'] as String,
reference: json['reference'] as String,
total: json['total_amount'] as int,
status: json['status'] as String,
);
final String id;
final String reference;
final int total;
final String status;
Order toEntity() => Order(
id: id,
reference: reference,
total: total,
status: OrderStatus.values.byName(status),
);
}If the API renames total_amount tomorrow, only this file changes. The rest of the app only sees the Order entity.
The data source, which makes the network call and nothing else:
// lib/features/orders/data/datasources/orders_api.dart
class OrdersApi {
OrdersApi(this._dio);
final Dio _dio;
Future<List<OrderModel>> fetchOrders() async {
final response = await _dio.get<List<dynamic>>('/orders');
return response.data!
.map((json) => OrderModel.fromJson(json as Map<String, dynamic>))
.toList();
}
}The repository implementation, which picks the source and converts to the domain. This is where offline logic lives, already mentioned in the patterns article:
// lib/features/orders/data/repositories/order_repository_impl.dart
class OrderRepositoryImpl implements OrderRepository {
OrderRepositoryImpl(this._api, this._cache);
final OrdersApi _api;
final OrdersCache _cache;
@override
Future<List<Order>> getOrders() async {
try {
final models = await _api.fetchOrders();
await _cache.save(models);
return models.map((m) => m.toEntity()).toList();
} on DioException {
final cached = await _cache.load();
return cached.map((m) => m.toEntity()).toList();
}
}
}Presentation, injection and tests
Presentation only knows the domain. The screen asks a dedicated class for a state (loading, data or error) and displays it. How that class is built, with Provider, Riverpod or Bloc, is the whole topic of the next article. What matters here: the widget no longer makes any network call.
Injection wires the layers in a single place, at app startup. With get_it:
// lib/injection.dart
final getIt = GetIt.instance;
void setupDependencies() {
getIt
..registerLazySingleton<Dio>(() => Dio(BaseOptions(baseUrl: Env.apiUrl)))
..registerLazySingleton(() => OrdersApi(getIt()))
..registerLazySingleton(() => OrdersCache())
..registerLazySingleton<OrderRepository>(
() => OrderRepositoryImpl(getIt(), getIt()),
)
..registerFactory(() => GetActiveOrders(getIt()));
}Tests become simple, because each layer is tested on its own. The use case is checked with a fake repository, without a network or Flutter, thanks to mocktail:
class MockOrderRepository extends Mock implements OrderRepository {}
void main() {
test('ignores cancelled orders', () async {
final repository = MockOrderRepository();
when(() => repository.getOrders()).thenAnswer((_) async => [
const Order(id: '1', reference: 'ORD-1', total: 15000, status: OrderStatus.paid),
const Order(id: '2', reference: 'ORD-2', total: 8000, status: OrderStatus.cancelled),
]);
final orders = await GetActiveOrders(repository)();
expect(orders.map((o) => o.id), ['1']);
});
}The final tree of a feature:
lib/
├── core/ # HTTP client, errors, theme, shared code
├── injection.dart
└── features/
└── orders/
├── domain/
│ ├── entities/order.dart
│ ├── repositories/order_repository.dart
│ └── usecases/get_active_orders.dart
├── data/
│ ├── models/order_model.dart
│ ├── datasources/orders_api.dart
│ └── repositories/order_repository_impl.dart
└── presentation/
├── pages/orders_page.dart
└── widgets/order_tile.dartWhen it's too much
Clean Architecture has a cost: for a single screen, you need about ten files. I don't apply it everywhere.
A prototype or an app with a few screens: one folder per feature with a repository is enough. No use cases, no separate models.
An app that will live and grow, with offline support, several data sources or a team: the full architecture pays for itself very quickly.
In between, I start with
dataandpresentation, and adddomainthe day a real business rule appears.
Splitting by feature (features/orders, features/auth), though, I always keep: it costs nothing and avoids the trap of global models/, screens/, services/ folders that grow forever.
Up next
One question remains: how does the presentation layer manage screen state? setState, Provider, Riverpod or Bloc? That's the topic of the last article in the series, on state management in Flutter.
Sources
Robert C. Martin, Clean Architecture: A Craftsman's Guide to Software Structure and Design, Prentice Hall, 2017
subscribe --blog
Get new posts by email
One email per new post, nothing else. Unsubscribe in one click.
Your address is only used to send you new posts. Privacy
ls ./related-articles



