Sub topic 5
Repositories and Data Sources in a Feature
This chapter assumes you know the repository pattern at a basic level, can read Dart imports and export, and have seen the feature folder layout from earlier chapters (data/, domain/, presentation/). It covers what goes inside a feature's data/ folder, how a repository hides its sources, and the mistakes that make the layer leak.
Why the data layer is split in two
A feature's data/ folder usually holds two kinds of classes:
- Data sources talk to one concrete thing: a REST endpoint, a local database,
shared_preferences, a platform channel. They return raw shapes such as JSON maps or generated DTOs (data transfer objects). - The repository implementation combines those sources and returns domain objects. It decides where data comes from, when to cache, and how to translate failures.
The repository interface lives in domain/, so the dependency points inward. Presentation code and state holders depend on CartRepository. Only the app shell knows which implementation is used.
What belongs where
| Class | Folder | Knows about | Returns |
|---|---|---|---|
| Entity such as `CartItem` | `domain/` | Nothing outside Dart | Itself |
| Repository interface | `domain/` | Entities, domain exceptions | Entities |
| DTO such as `CartItemDto` | `data/` | JSON or database column names | Itself, plus conversion methods |
| Data source | `data/` | One transport or storage API | DTOs or raw maps |
| Repository implementation | `data/` | Data sources, DTOs, domain types | Entities |
The key rule is that DTOs never leave data/. If a widget imports a DTO, a change to the server's JSON shape now changes the UI.
A complete example
The domain side has an entity, a repository interface, and a domain-level exception. Domain code does not import dart:io, http, or any storage package.
// lib/features/cart/domain/cart_item.dart
class CartItem {
const CartItem({required this.productId, required this.quantity});
final String productId;
final int quantity;
CartItem copyWith({int? quantity}) =>
CartItem(productId: productId, quantity: quantity ?? this.quantity);
}
// lib/features/cart/domain/cart_exception.dart
class CartStorageException implements Exception {
const CartStorageException(this.message);
final String message;
@override
String toString() => 'CartStorageException: $message';
}
// lib/features/cart/domain/cart_repository.dart
import 'cart_item.dart';
abstract interface class CartRepository {
Future<List<CartItem>> loadItems();
Future<void> addItem(CartItem item);
}The data side holds the DTO, the data source, and the repository implementation.
// lib/features/cart/data/cart_item_dto.dart
import '../domain/cart_item.dart';
class CartItemDto {
const CartItemDto({required this.productId, required this.quantity});
factory CartItemDto.fromJson(Map<String, Object?> json) {
final productId = json['product_id'];
final quantity = json['qty'];
if (productId is! String || quantity is! int) {
throw FormatException('Malformed cart row: $json');
}
return CartItemDto(productId: productId, quantity: quantity);
}
factory CartItemDto.fromDomain(CartItem item) =>
CartItemDto(productId: item.productId, quantity: item.quantity);
final String productId;
final int quantity;
Map<String, Object?> toJson() => {'product_id': productId, 'qty': quantity};
CartItem toDomain() => CartItem(productId: productId, quantity: quantity);
}
// lib/features/cart/data/cart_local_data_source.dart
abstract interface class CartLocalDataSource {
Future<List<Map<String, Object?>>> readAll();
Future<void> writeAll(List<Map<String, Object?>> rows);
}
class InMemoryCartLocalDataSource implements CartLocalDataSource {
List<Map<String, Object?>> _rows = const [];
@override
Future<List<Map<String, Object?>>> readAll() async => _rows;
@override
Future<void> writeAll(List<Map<String, Object?>> rows) async {
_rows = List.unmodifiable(rows);
}
}
// lib/features/cart/data/default_cart_repository.dart
import '../domain/cart_exception.dart';
import '../domain/cart_item.dart';
import '../domain/cart_repository.dart';
import 'cart_item_dto.dart';
import 'cart_local_data_source.dart';
class DefaultCartRepository implements CartRepository {
DefaultCartRepository(this._local);
final CartLocalDataSource _local;
@override
Future<List<CartItem>> loadItems() async {
try {
final rows = await _local.readAll();
return rows
.map((row) => CartItemDto.fromJson(row).toDomain())
.toList(growable: false);
} on FormatException catch (e) {
throw CartStorageException(e.message);
}
}
@override
Future<void> addItem(CartItem item) async {
final items = (await loadItems()).toList();
final index = items.indexWhere((i) => i.productId == item.productId);
if (index >= 0) {
items[index] =
items[index].copyWith(quantity: items[index].quantity + item.quantity);
} else {
items.add(item);
}
await _local.writeAll(
items.map((i) => CartItemDto.fromDomain(i).toJson()).toList(),
);
}
}Three details are worth noting:
addItemmerges quantities. That is business behavior, but here it is a storage-level merge of rows. If the rule grows (stock limits, price checks), move it into a domain use case and keep the repository to loading and saving.fromJsonvalidates types instead of casting withas. A bad row fails with a clearFormatExceptionat the boundary, not with aTypeErrordeep in a widget.- The repository converts
FormatExceptionintoCartStorageException. Callers never need to know that the storage was JSON-like rows.
Translating errors at the boundary
Each data source throws its own exceptions: SocketException, DioException, DatabaseException. If these reach the UI, presentation code has to import the networking package, and the data layer is no longer replaceable.
The repository is the translation point. It catches source-specific exceptions and throws a small set of domain exceptions, such as CartStorageException or a NetworkUnavailable type. Alternatively it returns a result type. Pick one style per project and use it in every feature. Mixing exceptions in one feature and result types in another forces every consumer to remember which is which.
Combining sources: caching and offline
A repository with one source is just a wrapper. The layer earns its place once there are two. A common shape is a remote source, a local cache, and a policy:
- Read: return cached rows if they are fresh, otherwise fetch, write to the cache, and return.
- Write: send to the server first, update the cache only on success. Or write locally and queue the sync. Choose deliberately, because the two choices behave differently when the device is offline.
- Failure on refresh: if the fetch fails and a cache exists, return stale data and let the caller know it is stale. Silently swallowing the error hides outages.
Keep this policy inside the repository, not in controllers. If a state holder decides whether to call the cache or the network, the policy is duplicated in every screen that loads the same data.
Where the interface lives, and when it is worth it
The repository interface goes in domain/. That placement is what allows presentation to depend on an abstraction while data/ depends on domain/. It also lets tests replace the repository with a fake without touching network code.
Data source interfaces are different. They are internal to the feature, so they can sit in data/ next to their implementations. You do not need an interface for every data source. Add one when you want to swap an implementation in tests, or when two real implementations exist (for example SQLite on mobile and IndexedDB on web). A single-implementation interface that nobody fakes is extra code to maintain.
Do not export data sources or DTOs from the feature's barrel file. The public API from the earlier chapter exports the entity and the repository interface. Everything in data/ stays private by convention.
Sharing data sources between features
Two features sometimes need the same endpoint, such as the catalog and the cart both reading product prices. Resist the shortcut of importing one feature's data source into the other. Options, in order of preference:
- Each feature owns a small data source for the calls it needs. Duplication of a few lines of request code is cheaper than coupling.
- If the call is generic infrastructure (an HTTP client, an auth interceptor, a database handle), put it in
core/network/and inject it into each feature's data sources. - If one feature genuinely owns the data, it exposes a repository interface through its barrel file, and the other feature depends on that interface.
Testing the data layer
Repository tests need only a fake data source, and the file path mirrors the feature.
// test/features/cart/data/default_cart_repository_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:shop/features/cart/data/cart_local_data_source.dart';
import 'package:shop/features/cart/data/default_cart_repository.dart';
import 'package:shop/features/cart/domain/cart_exception.dart';
import 'package:shop/features/cart/domain/cart_item.dart';
void main() {
test('addItem merges quantities for the same product', () async {
final repo = DefaultCartRepository(InMemoryCartLocalDataSource());
await repo.addItem(const CartItem(productId: 'a', quantity: 1));
await repo.addItem(const CartItem(productId: 'a', quantity: 2));
final items = await repo.loadItems();
expect(items, hasLength(1));
expect(items.single.quantity, 3);
});
test('malformed rows become CartStorageException', () async {
final local = InMemoryCartLocalDataSource();
await local.writeAll([
{'product_id': 'a'},
]);
expect(
DefaultCartRepository(local).loadItems(),
throwsA(isA<CartStorageException>()),
);
});
}This assumes the app package is named shop. Adjust the import prefix to match your pubspec.yaml.
Common errors
- Business rules in data sources. Sources should fetch and store. Pricing, validation, and merging rules belong in the domain.
- Repositories that return
Map<String, dynamic>. This pushes parsing into callers and removes type checking. - One giant repository per app. Keep repositories scoped to a feature's aggregate. A
CartRepositorythat also loads products and user profiles is three features in one class. - Interface in
data/. If the interface sits next to its implementation, presentation must import fromdata/, which breaks the inward dependency rule. - Constructing dependencies inside the repository.
DefaultCartRepositorytakes its source through the constructor. Creating an HTTP client inside the class makes it impossible to fake and hides wiring from the app shell.
Exercise
A teammate's CartController in presentation/ imports CartItemDto and DioException to handle a failed request. Which two changes in the data/ and domain/ folders remove those imports, and why does each help?
Show answer
First, have the repository's loadItems convert DTOs to CartItem with toDomain() so the controller only sees domain entities. Second, catch DioException inside the repository and throw a domain exception such as CartStorageException or a NetworkUnavailable type defined in domain/. The controller then depends only on domain types, so changing the JSON shape or replacing Dio affects only the data/ folder.
Exercise
The catalog and cart features both call GET /products/{id}. Which option keeps features independent, and what do you share if you need to avoid duplicating the HTTP setup?
Show answer
Give each feature its own small data source for the calls it needs. Share only generic infrastructure, such as the configured HTTP client, from core/network/ and inject it into each data source. Do not import one feature's data source into the other.