Sub topic 3
What goes inside a feature folder
This chapter assumes you can build a Flutter app with widgets and navigation, and that you know Dart imports and the export directive. It also assumes you have used one state management approach and know the repository pattern. By the end you will be able to lay out a feature folder, say which file belongs in which sublayer, and spot the usual mistakes.
The feature folder is a small app
A feature is one user-facing capability, such as the cart, the catalog, or sign-in. Its folder holds everything needed to build that capability: screens, business rules, and the code that talks to storage or the network. You should be able to read the folder and understand the feature without opening anything else, apart from the shared code it depends on.
Here is the layout this tutorial uses for a cart feature, with the matching test folder:
lib/
main.dart
app/
app.dart
router.dart
core/
network/
theme/
widgets/
features/
catalog/
catalog.dart
catalog_routes.dart
data/
domain/
presentation/
cart/
cart.dart
cart_routes.dart
data/
domain/
presentation/
test/
features/
cart/
data/
domain/
presentation/Each feature has three sublayers and two files at its root:
presentation/holds what the user sees and touches.domain/holds the feature's concepts and rules.data/holds how those concepts are stored and fetched.cart.dartis the public entry file (the barrel file) that decides what other code may import.cart_routes.dartdeclares the feature's routes.
The folders app/ and core/ sit outside any feature. Later chapters cover what belongs in core/, how routes are combined, and how the barrel file is used.
The three sublayers
The diagram shows which sublayer may import which. The arrows point from the importing layer to the layer it depends on.
The domain layer imports nothing from the other two. Presentation and data do not import each other. That keeps the center of the feature easy to test and easy to understand.
Domain: the feature's vocabulary
The domain layer holds the plain Dart types that describe the feature, plus the interfaces it needs from the outside world. Typical contents:
- Entities, such as
CartItem. - Repository interfaces, such as
CartRepository. - Optional use-case classes, when a rule spans several repository calls.
- Value types and small exceptions, such as
OutOfStockException.
Domain files should not import package:flutter, dio, sqflite, or any other framework or storage package. If a domain file needs a widget or an HTTP client, the code probably belongs in another layer.
// lib/features/cart/domain/cart_item.dart
class CartItem {
const CartItem({
required this.productId,
required this.name,
required this.quantity,
});
final String productId;
final String name;
final int quantity;
CartItem copyWith({int? quantity}) => CartItem(
productId: productId,
name: name,
quantity: quantity ?? this.quantity,
);
}// lib/features/cart/domain/cart_repository.dart
import 'cart_item.dart';
abstract interface class CartRepository {
Future<List<CartItem>> loadItems();
Future<void> addItem(CartItem item);
}Data: how the domain is fulfilled
The data layer implements the domain's interfaces. It is the only place that knows about JSON, SQL, HTTP status codes, or a particular storage package. Typical contents:
- Repository implementations.
- Data sources, which are thin wrappers around one remote or local system.
- DTOs (data transfer objects), which mirror the shape of external data.
- Mappers that turn DTOs into domain entities.
// lib/features/cart/data/in_memory_cart_repository.dart
import '../domain/cart_item.dart';
import '../domain/cart_repository.dart';
class InMemoryCartRepository implements CartRepository {
final List<CartItem> _items = [];
@override
Future<List<CartItem>> loadItems() async => List.unmodifiable(_items);
@override
Future<void> addItem(CartItem item) async {
_items.add(item);
}
}A DTO and its mapper show why the split matters. The server's field names stay in the data layer, and the rest of the feature sees only CartItem:
// lib/features/cart/data/cart_item_dto.dart
import '../domain/cart_item.dart';
class CartItemDto {
const CartItemDto({
required this.sku,
required this.title,
required this.qty,
});
factory CartItemDto.fromJson(Map<String, Object?> json) => CartItemDto(
sku: json['sku'] as String,
title: json['title'] as String,
qty: json['qty'] as int,
);
final String sku;
final String title;
final int qty;
CartItem toDomain() =>
CartItem(productId: sku, name: title, quantity: qty);
}If the backend renames qty to quantity, only this file changes.
Presentation: screens and their state
The presentation layer holds pages, feature-specific widgets, and the objects that hold screen state (controllers, notifiers, cubits, or view models, depending on your approach). It imports domain types and repository interfaces. It never imports a concrete repository from data/.
// lib/features/cart/presentation/cart_page.dart
import 'package:flutter/material.dart';
import '../domain/cart_item.dart';
import '../domain/cart_repository.dart';
class CartPage extends StatefulWidget {
const CartPage({super.key, required this.repository});
final CartRepository repository;
@override
State<CartPage> createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
late final Future<List<CartItem>> _items = widget.repository.loadItems();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Cart')),
body: FutureBuilder<List<CartItem>>(
future: _items,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final items = snapshot.requireData;
return ListView(
children: [
for (final item in items)
ListTile(
title: Text(item.name),
trailing: Text('x${item.quantity}'),
),
],
);
},
),
);
}
}The page receives a CartRepository through its constructor. It does not know whether the implementation is in memory, backed by a database, or a test fake. Who supplies the repository is decided at the app level, which a later chapter covers.
A real feature will usually split presentation/ further, for example into pages/, widgets/, and a state folder. Do that when the folder gets crowded, not before.
Where each kind of file goes
| File | Sublayer | Reason |
|---|---|---|
| `CartItem` entity | `domain/` | Plain Dart, describes the feature |
| `CartRepository` interface | `domain/` | Says what the feature needs, not how |
| `CartItemDto` | `data/` | Mirrors external data shape |
| `InMemoryCartRepository` | `data/` | Implements the interface |
| `CartPage` | `presentation/` | Builds widgets |
| Cart state holder | `presentation/` | Exists to serve a screen |
| `cart_routes.dart` | feature root | Wires pages to paths |
| `cart.dart` | feature root | Public entry file |
When you are unsure, ask what would change the file. If a design change would edit it, it is presentation. If a business rule change would edit it, it is domain. If a backend or storage change would edit it, it is data.
The root files
The feature root contains only the files that face outward. The barrel file lists what other code may import:
// lib/features/cart/cart.dart
// Public API of the cart feature. Other features import only this file.
export 'cart_routes.dart';
export 'domain/cart_item.dart';
export 'domain/cart_repository.dart';It does not export data/in_memory_cart_repository.dart, CartItemDto, or the pages. Those remain internal. The routes file declares the feature's screens:
// lib/features/cart/cart_routes.dart
import 'package:go_router/go_router.dart';
import 'presentation/cart_page.dart';
final cartRoutes = <RouteBase>[
GoRoute(
path: '/cart',
builder: (context, state) => const CartPage(),
),
];As written, this route does not compile, because CartPage now requires a repository argument. The feature has to get its repository from somewhere, such as a dependency injection container, an inherited widget, or a builder passed in at the app level. Which one you choose depends on your state management approach, and the chapters on feature state and app composition resolve it. Do not fix it by importing InMemoryCartRepository into the page, because that breaks the dependency rule shown in the diagram.
Common mistakes
- Everything in
presentation/. Entities, API calls, and widgets in one folder gives you a feature that is just a small layer-first app. Move types and interfaces todomain/and implementations todata/. - Flutter imports in
domain/. AColororIconDatafield on an entity ties your rules to the UI framework. Store a plain value and convert it in presentation. - DTOs reaching widgets. If a page reads
dto.sku, the backend shape has leaked. Map to entities at the data boundary. - Empty ceremony. A feature that only shows a static settings screen does not need
domain/anddata/. Create a sublayer when you have something to put in it. - Folders named after types. A
models/folder inside a feature sends you back to grouping by technical kind. Name the sublayer by its responsibility. - Features named after screens.
cart_pageis a screen.cartis the feature. A feature normally owns several screens.
Exercise
A teammate adds CartItemDto to lib/features/cart/domain/ and uses it in CartPage to read dto.sku. Name two problems with this and say where the class and the conversion should live.
Show answer
First, the DTO mirrors the backend's JSON shape, so putting it in domain/ ties the feature's vocabulary to an external format. Second, using it in CartPage leaks that format into the UI, so a backend field rename would force UI changes. Move CartItemDto to data/, add a toDomain() mapper there, have the repository implementation return CartItem objects, and let CartPage read only CartItem through CartRepository.
Exercise
You are adding a wishlist feature. List the files you would create for an Item entity, a repository that stores wishlist items on the server, and a screen that lists them, and name the folder for each.
Show answer
features/wishlist/domain/wishlist_item.dart for the entity and features/wishlist/domain/wishlist_repository.dart for the interface. features/wishlist/data/ gets the repository implementation, any DTO, and a remote data source. features/wishlist/presentation/wishlist_page.dart holds the screen. At the feature root, add wishlist.dart (barrel file) and wishlist_routes.dart.