Sub topic 10
When one feature needs another
This chapter assumes you know the feature folder layout, the dependency direction rules (features may depend on core, never the reverse), and the barrel file for a feature's public API from earlier chapters. You should also be comfortable with go_router and with passing objects through constructors.
The problem
Features are meant to be independent, but real screens are not. Checkout shows how many items are in the cart. The catalog has an "Add to cart" button. A profile page links to order history. Each of these crosses a feature boundary.
If you answer by importing whatever file is convenient, you end up with the tangle that feature-first structure was meant to prevent. Features reach into each other's data folders, two features import each other, and a change in one breaks the other.
The aim is to let features cooperate while keeping the dependencies visible, one-directional, and narrow.
Four ways to cross a boundary
Pick the lightest option that solves the problem.
| Approach | Use it when | Coupling |
|---|---|---|
| Import the other feature's barrel file | One feature genuinely builds on another, and the direction is clear | Compile-time dependency on the public API |
| Shared contract in `core` | A feature needs a small capability, not the whole other feature | Depends only on an interface |
| Navigation by route path and parameters | You only need to move the user to another feature's screen | Depends on a path string |
| Data passed in by the app shell | The app already holds the value and can hand it down | None between the features |
All four share one rule: a feature never imports another feature's data, domain, or presentation folders directly. It uses the other feature's barrel file or something in core.
Option 1: import the public API
The simplest case is a one-way dependency. Checkout is built on top of the cart, so it may import the cart's barrel file:
import '../../cart/cart.dart';The barrel file lists what cart chooses to expose. If checkout needs something not in that list, you have two honest choices. Add it to the barrel on purpose, or reconsider whether checkout needs it. Reaching around the barrel into cart/data/... is the shortcut to avoid.
This option works while the dependency graph between features stays acyclic. Checkout may depend on cart. Cart must then never depend on checkout, directly or through a chain of other features.
Option 2: a shared contract
Sometimes importing the whole feature is too much. Checkout only wants the item count, and it should not care how the cart stores items. Define the contract in shared code and let the app shell connect the two sides. The contract is the same as the one in the spine:
// lib/core/contracts/cart_summary.dart
abstract interface class CartSummary {
int get itemCount;
}Checkout depends only on this interface:
// 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}')),
);
}
}The cart feature supplies the real state. Here it is a small ChangeNotifier that the cart's own screens also use:
// lib/features/cart/presentation/cart_controller.dart
import 'package:flutter/foundation.dart';
import '../domain/cart_item.dart';
class CartController extends ChangeNotifier {
final List<CartItem> _items = [];
List<CartItem> get items => List.unmodifiable(_items);
void add(CartItem item) {
_items.add(item);
notifyListeners();
}
}The barrel file then needs to export CartController. That is a deliberate addition to the public API, because the app shell needs it:
// lib/features/cart/cart.dart
export 'cart_routes.dart';
export 'domain/cart_item.dart';
export 'domain/cart_repository.dart';
export 'presentation/cart_controller.dart';The adapter lives in the app shell, the only place allowed to know both sides:
// lib/app/cart_summary_adapter.dart
import '../core/contracts/cart_summary.dart';
import '../features/cart/cart.dart';
class CartControllerSummary implements CartSummary {
CartControllerSummary(this._controller);
final CartController _controller;
@override
int get itemCount => _controller.items.length;
}Neither feature knows the other exists. The only thing they share is a three-line interface.
Connecting the pieces in the app shell
Checkout's routes now need a CartSummary. Because a top-level final list cannot receive arguments, make the routes a function:
// lib/features/checkout/checkout_routes.dart
import 'package:go_router/go_router.dart';
import '../../core/contracts/cart_summary.dart';
import 'presentation/checkout_page.dart';
List<RouteBase> checkoutRoutes({required CartSummary cart}) => [
GoRoute(
path: '/checkout',
builder: (context, state) => CheckoutPage(cart: cart),
),
];The router takes the dependency and passes it on:
// lib/app/router.dart
import 'package:go_router/go_router.dart';
import '../core/contracts/cart_summary.dart';
import '../features/cart/cart.dart';
import '../features/checkout/checkout_routes.dart';
GoRouter buildRouter({required CartSummary cartSummary}) {
return GoRouter(
routes: [
...cartRoutes,
...checkoutRoutes(cart: cartSummary),
],
);
}All the dependency arrows point toward core or originate in the app shell. No arrow connects checkout and cart.
Option 3: navigate by path
Linking to a screen in another feature does not need a code dependency on its widgets. A route path is enough:
// inside any feature's widget
context.go('/cart');Raw strings drift. If cart renames its path, every caller breaks silently at runtime. A better approach is to have the owning feature expose its path as a constant in its barrel:
// lib/features/cart/cart_routes.dart
import 'package:go_router/go_router.dart';
import 'presentation/cart_page.dart';
const cartPath = '/cart';
final cartRoutes = <RouteBase>[
GoRoute(
path: cartPath,
builder: (context, state) => const CartPage(),
),
];Callers import cart.dart and use cartPath. Where that would create a feature-to-feature import you want to avoid, pass the destination in as a callback or a path parameter from the app shell instead. Keep route parameters small and primitive, such as an ID. Do not pass another feature's domain objects through extra, because that quietly couples the types.
Option 4: data from the app shell
Some values are app-wide: the signed-in user, the selected locale, the current theme mode. The shell owns them and either hands them to features through constructors or exposes them through your state management solution at a level above all features. If two features both read the same value, that value probably belongs in core or in the shell, not in either feature.
Breaking cycles
Cycles are the main failure of cross-feature design. A typical one: catalog imports cart to add items, and cart imports catalog to show product names. Dart permits circular imports between libraries, so the compiler will not stop you. The damage appears later, when neither feature can be tested or moved to a package on its own.
Three fixes work, in this order of preference:
- Pass data instead of importing. Cart stores the product name it received when the item was added, so it never needs catalog types.
- Extract the shared concept. If both need a
MoneyorProductIdtype, move it tocore. - Invert one direction with a contract. Catalog depends on a
CartActionsinterface incore, and the shell binds it to cart.
Choosing between the options
Ask these questions in order:
- Do I only need to send the user somewhere? Use the route path.
- Do I need a value the app shell already has? Pass it down.
- Do I need one or two capabilities from another feature? Use a contract in
core. - Is my feature fundamentally built on another, with a clear one-way direction? Import its barrel file.
If you reach for a deep import, stop. It means the public API is missing something, or the boundary is in the wrong place.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Importing `../cart/data/...` from another feature | A refactor inside cart breaks checkout | Import `cart.dart` or use a contract |
| Putting feature-specific types in `core/contracts` | `core` starts depending on features | Keep contracts to primitives and `core` types |
| Constructing the adapter inside a feature | The feature knows its neighbor again | Build adapters only in `app` |
| Sharing one mutable object across features by singleton | Hidden coupling and test leaks | Pass it in through the constructor |
| Passing domain objects through `GoRouter` `extra` | Type casts fail after deep links or restoration | Pass an ID and reload it |
Testing across the boundary
Contracts make cross-feature tests simple. Checkout tests supply a fake without importing anything from cart:
// test/features/checkout/presentation/checkout_page_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/core/contracts/cart_summary.dart';
import 'package:my_app/features/checkout/presentation/checkout_page.dart';
class FakeCartSummary implements CartSummary {
@override
int get itemCount => 3;
}
void main() {
testWidgets('shows the item count', (tester) async {
await tester.pumpWidget(
MaterialApp(home: CheckoutPage(cart: FakeCartSummary())),
);
expect(find.text('Items: 3'), findsOneWidget);
});
}A test for the adapter itself belongs next to the app shell, because that is where the two features meet.
Exercise
The catalog feature imports the cart barrel to add items, and the cart feature imports the catalog barrel to show product names. Name the problem and give two ways to fix it.
Show answer
The two features form an import cycle, so neither can be tested or extracted into a package without the other. Fix it by having cart store the product name it receives when an item is added, so it no longer imports catalog. Alternatively, move the shared concept, such as a product ID type, into core, or give catalog a small CartActions interface in core that the app shell binds to the cart.
Exercise
Why is CartControllerSummary placed in lib/app and not in the checkout or cart feature?
Show answer
The adapter knows about both the cart's CartController and the core contract. Placing it in either feature would make that feature depend on knowledge of the other side's needs. The app shell is the one place allowed to import many features, so it is the right place to connect them.