Sub topic 7
Dependency Rules Between Features and Shared Code
This chapter assumes you can build Flutter apps with widgets and navigation, you know how Dart import and export work, you have used one state management approach, and you know the repository pattern. It covers the rules that decide which folder may import which. Folder names alone do not keep features independent. Import rules do.
Why rules matter more than folders
A feature-first tree looks tidy on day one. Six months later, cart imports catalog/data/product_dto.dart, catalog imports a widget from cart/presentation, and the two features cannot change separately. The folders still look correct, but the structure is gone.
Dependency rules are a short list of allowed import directions. If you can state them in a few sentences and check them in a code review, they hold. If they exist only as habit, they erode.
The three kinds of code
Every file in lib/ belongs to one of three groups.
- Feature code lives in
lib/features/<name>/. It implements one product capability, such as cart or catalog. - Shared code lives in
lib/core/. It has no knowledge of any feature. Examples are the HTTP client setup, the theme, and generic widgets such as a loading spinner. - App shell code lives in
lib/app/andlib/main.dart. It knows every feature and wires them together.
The rules below are written in terms of these groups.
The core rules
- Shared code never imports feature code.
coremust compile if you delete every feature. - A feature may import
core. This is the normal way to reuse the theme, network client, and common widgets. - A feature never imports another feature's internals. It may import only the other feature's public file, and only when rule 5 allows it.
- Only the app shell imports many features.
appcomposes features. Features do not compose each other. - Prefer no feature-to-feature dependency at all. When one feature needs data or behavior from another, depend on a small interface in
coreand let the app shell supply the implementation.
Arrows point from the importing code to the imported code. There is no arrow between features and no arrow out of core. Any import that would add such an arrow breaks a rule.
Dependency direction inside a feature
Each feature has three parts: presentation, domain, and data. The same idea applies inside the folder. Dependencies point toward domain.
| Part | May import | Must not import |
|---|---|---|
| `presentation` | `domain`, `core`, Flutter | `data` |
| `domain` | `core` (only plain Dart parts) | `presentation`, `data`, Flutter widgets |
| `data` | `domain`, `core` | `presentation` |
The domain layer holds entities and repository interfaces. The data layer implements those interfaces. Presentation code asks for the abstraction and never learns which implementation it receives.
// lib/features/cart/domain/cart_repository.dart
import 'cart_item.dart';
abstract interface class CartRepository {
Future<List<CartItem>> loadItems();
Future<void> addItem(CartItem item);
}
// 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);
}
}InMemoryCartRepository imports the domain files. The domain files know nothing about it. You can replace it with an HTTP-backed version, or a fake in tests, without editing a presentation file.
Where the data layer gets wired
Presentation code needs an instance of CartRepository, but it must not import InMemoryCartRepository. The wiring happens in a place allowed to see both, which is usually the feature's own dependency-injection setup or the app shell. Which tool you use (Provider, Riverpod, get_it, constructor arguments) does not change the rule. Only the wiring location sees the concrete class.
Deciding what is shared
The most common violation of rule 1 starts as an honest attempt to avoid duplication. A developer moves a widget into core because two features use it. Later that widget needs a Product class, so core imports catalog. Now shared code depends on a feature.
Use these tests before moving anything to core.
- Does it mention a domain concept? If the code refers to products, carts, or orders, it is feature code. It does not belong in
core. - Is it used by more than one feature today? Code used by one feature stays there. Two real users justify sharing. A guess about future use does not.
- Would it make sense in a different app? A
PrimaryButtonor an HTTP client wrapper would. AProductPriceTagwould not.
A small amount of duplication between features is often cheaper than a shared module that every feature must coordinate around.
When two features need each other
Suppose checkout needs to show how many items are in the cart. The direct approach is import '../../cart/data/...'. That violates rule 3. Importing cart/cart.dart is better, but it still creates a feature-to-feature dependency, and a cycle appears if cart later needs something from checkout.
The approach in rule 5 inverts the dependency. Define a small interface in core, let checkout depend on it, and let the app shell provide a cart-backed implementation.
// lib/core/contracts/cart_summary.dart
abstract interface class CartSummary {
int get itemCount;
}
// lib/features/checkout/presentation/checkout_page.dart
import 'package:flutter/material.dart';
import '../../../core/contracts/cart_summary.dart';
class CheckoutPage extends StatelessWidget {
const CheckoutPage({super.key, required this.cart});
final CartSummary cart;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('Items: ${cart.itemCount}')),
);
}
}Checkout now compiles and can be tested without the cart feature present. The cart feature (or the app shell, if you prefer to keep cart unaware of the contract) provides a class that implements CartSummary.
The interface in core must stay small and free of domain models. CartSummary exposes an int, not a CartItem. If the contract starts to need cart entities, the features are probably too tightly coupled, and you should reconsider where the boundary lies.
Choosing between the options
| Approach | Coupling | Use when |
|---|---|---|
| Import the other feature's public file | Compile-time, direct | One-way, stable need, such as navigating to a page |
| Interface in `core`, implemented in the app shell | Interface only | The need is data or behavior and you want tests without the other feature |
| Pass values through route parameters | None beyond the route | Handing over an ID or a small value |
Public files and the importing rule
Rule 3 refers to a feature's "public file". Each feature exposes a barrel file such as lib/features/cart/cart.dart that re-exports only what others may use. The next chapter covers the barrel in detail. For dependency purposes, the rule is simple: from outside a feature, the only allowed import path is features/<name>/<name>.dart. A line such as import '../cart/data/in_memory_cart_repository.dart' in another feature is a violation, even though Dart allows it.
Dart has no package-private visibility for folders. The language will not stop a bad import. The boundary exists only because your team respects it, or because a tool checks it.
Common errors
- Importing across features through a relative path.
../../cart/presentation/cart_page.dartcompiles and silently couples the features. Search forfeatures/<other>/inside each feature to find these. - Domain code importing Flutter. If
domainimportspackage:flutter/material.dart, it can no longer be tested as plain Dart, and it signals that UI concerns have leaked in. - Putting a feature's models in
core"for convenience". This reverses rule 1 indirectly. Other features begin to depend oncorefor cart concepts and the cart feature loses ownership. - Circular feature imports. If A imports B and B imports A, neither can change without the other. Break the cycle with an interface in
core, or merge the two features if they are really one. - The app shell growing business logic. The shell may construct and connect. It should not decide how a cart total is calculated.
A quick review checklist
- Does any file in
coreimport fromfeatures/? It must not. - Does any feature import
features/<other>/with a path that does not end in the other feature's barrel file? - Does any
domainfile importdataorpresentation? - Does any
presentationfile import a concrete class fromdata? - Is any feature importing a feature that imports it back?
Run these checks by searching imports, for example with grep -rn "features/" lib/core. Later chapters automate them so they run on every pull request.
Exercise
A ProductPriceTag widget is used by both the catalog and cart features, and a developer moves it to lib/core/widgets/. It takes a Product object from catalog/domain. Which rule does this break, and what are two ways to fix it?
Show answer
It breaks rule 1, because core now imports feature code (catalog). One fix is to keep the widget in a feature and have the other feature receive only plain values. Another is to change the widget to take plain values such as a String name and an int priceInCents, so it no longer depends on Product. With plain parameters the widget names no domain concept, so it can stay in core, although a price formatter is still more generic than a product-specific tag.
Exercise
Checkout needs the number of items in the cart. List the files and folders you would create or edit so that checkout never imports the cart feature, and say which folder holds the cart-backed implementation.
Show answer
Create lib/core/contracts/cart_summary.dart with an abstract interface class CartSummary { int get itemCount; }. Make CheckoutPage take a CartSummary through its constructor. Write a class that implements CartSummary using the cart repository, and place it in the app shell (for example under lib/app/), where importing both features is allowed. The shell passes that instance to CheckoutPage when it builds the checkout route.