Sub topic 11
Wiring Features Together in the App Shell
This chapter assumes you have read the earlier chapters on feature anatomy, dependency rules, public barrel files, per-feature routes, and cross-feature contracts. It also assumes you know go_router basics and one way to expose state, here a ChangeNotifier. The chapter shows where all the pieces from those chapters meet.
What the app shell is for
The app shell is the code in lib/main.dart and lib/app/. It is the only place that is allowed to know every feature exists. Its work comes down to four jobs:
- Create the long-lived objects: repositories, controllers, and HTTP clients.
- Hand each feature the dependencies it asked for.
- Combine every feature's routes into one router.
- Provide the top-level
MaterialApp, theme, and error handling.
The shell has no business logic. If you find yourself writing a rule such as "free shipping above 50 euros" in app/, move it into a feature.
Dependencies point one way. The shell imports features through their barrel files and imports core/. Features import core/ but never import app/.
The composition root
A composition root is the single place where objects are constructed and connected. In this project it is AppDependencies, created once at startup.
The cart feature exposes CartController, a ChangeNotifier that wraps the repository. The checkout feature depends only on the CartSummary interface from core/contracts. The shell connects the two with a small adapter.
// lib/features/cart/domain/cart_item.dart
class CartItem {
const CartItem({required this.id, required this.name});
final String id;
final String name;
}
// lib/features/cart/presentation/cart_controller.dart
import 'package:flutter/foundation.dart';
import '../domain/cart_item.dart';
import '../domain/cart_repository.dart';
class CartController extends ChangeNotifier {
CartController(this._repository);
final CartRepository _repository;
List<CartItem> _items = const [];
List<CartItem> get items => _items;
Future<void> load() async {
_items = await _repository.loadItems();
notifyListeners();
}
Future<void> add(CartItem item) async {
await _repository.addItem(item);
await load();
}
}The barrel file from earlier chapters now needs two more lines, because the shell must construct the controller and the repository implementation:
// lib/features/cart/cart.dart
export 'cart_routes.dart';
export 'data/in_memory_cart_repository.dart';
export 'domain/cart_item.dart';
export 'domain/cart_repository.dart';
export 'presentation/cart_controller.dart';Now the shell. The adapter implements the shared contract on top of the cart feature, so neither feature imports the other.
// lib/app/dependencies.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;
}
class AppDependencies {
AppDependencies({required this.cartController})
: cartSummary = CartControllerSummary(cartController);
factory AppDependencies.create() {
return AppDependencies(
cartController: CartController(InMemoryCartRepository()),
);
}
final CartController cartController;
final CartSummary cartSummary;
}The constructor accepts a controller so tests can pass a fake repository. The create factory is what production uses.
Features that need dependencies expose route builders
Earlier, cartRoutes was a top-level final list. That works while a page needs nothing from outside. Once a page needs a controller, a global list cannot receive it. Replace the list with a function that takes the dependencies as parameters:
// lib/features/cart/cart_routes.dart
import 'package:go_router/go_router.dart';
import 'presentation/cart_controller.dart';
import 'presentation/cart_page.dart';
List<RouteBase> buildCartRoutes(CartController controller) => [
GoRoute(
path: '/cart',
builder: (context, state) => CartPage(controller: controller),
),
];
// 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> buildCheckoutRoutes({required CartSummary cart}) => [
GoRoute(
path: '/checkout',
builder: (context, state) => CheckoutPage(cart: cart),
),
];CartPage takes the controller in its constructor and listens to it with ListenableBuilder. The route function only passes the object along. It does not create it.
Combining routes and starting the app
The router, the app widget, and main each have a small job.
// lib/app/router.dart
import 'package:go_router/go_router.dart';
import '../features/cart/cart.dart';
import '../features/catalog/catalog.dart';
import '../features/checkout/checkout.dart';
import 'dependencies.dart';
GoRouter buildRouter(AppDependencies deps) {
return GoRouter(
initialLocation: '/catalog',
routes: [
...catalogRoutes,
...buildCartRoutes(deps.cartController),
...buildCheckoutRoutes(cart: deps.cartSummary),
],
);
}
// lib/app/app.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class App extends StatelessWidget {
const App({super.key, required this.router});
final GoRouter router;
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Shop',
routerConfig: router,
);
}
}
// lib/main.dart
import 'package:flutter/material.dart';
import 'app/app.dart';
import 'app/dependencies.dart';
import 'app/router.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final deps = AppDependencies.create();
await deps.cartController.load();
runApp(App(router: buildRouter(deps)));
}Three details matter here:
buildRouterruns once, outside anybuildmethod. If you create aGoRouterinsidebuild, every rebuild resets navigation to the initial location.- The shell owns the
/catalog,/cart, and/checkoutpaths only by combining the lists. Each feature still decides its own paths. mainis the only place that awaits startup work. Features should not assume that someone else already loaded their data.
Where state lives
State has a lifetime, and the lifetime decides where it is created.
| State | Created in | Lives as long as |
|---|---|---|
| `CartController` (cart contents) | App shell | The whole app run |
| Form state of the checkout page | The checkout page's own `State` | While the page is on screen |
| Theme mode | App shell | The whole app run |
| Search text on the catalog page | Catalog presentation code | While the page is on screen |
Objects that several features read, or that must survive navigation, belong in the shell. Everything else stays inside the feature that uses it. A good test is to ask who else would be surprised if this object were disposed. If nobody, keep it local.
Testing the shell
A shell smoke test checks that the wiring is correct without exercising feature internals. Because AppDependencies accepts its parts, you can build one with a prepared controller.
// test/app/app_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:shop/app/app.dart';
import 'package:shop/app/dependencies.dart';
import 'package:shop/app/router.dart';
import 'package:shop/features/cart/cart.dart';
void main() {
testWidgets('checkout shows the number of items in the cart',
(tester) async {
final controller = CartController(InMemoryCartRepository());
await controller.add(const CartItem(id: '1', name: 'Mug'));
final router = buildRouter(AppDependencies(cartController: controller));
await tester.pumpWidget(App(router: router));
router.go('/checkout');
await tester.pumpAndSettle();
expect(find.text('Items: 1'), findsOneWidget);
});
}This test fails if the adapter is missing, if the route is not registered, or if the checkout page receives a different CartSummary from the one the cart updates.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Navigation jumps back to the first page after a rebuild | `GoRouter` created inside `build` | Create it once in `main` or in a `State.initState` |
| Cart count in checkout stays at zero | Two `CartController` instances, one in the shell and one created in a page | Create the controller only in `AppDependencies` and pass it down |
| A feature imports `app/dependencies.dart` | The feature reaches for global state instead of taking a parameter | Add a constructor parameter or a route-builder argument |
| Two features both register `/profile` | Paths are global to the router | Prefix each feature's paths, for example `/account/profile` |
| Cart page is empty on first launch | `load()` was never called | Await it in `main`, or call it from the controller's creator |
Keeping the shell small
As features grow, AppDependencies grows too. Watch for these signs:
- The class creates more than about ten objects. Split it into one small builder function per feature, such as
buildCartModule(), that returns what the feature needs. - The router file mixes route lists with redirect logic. Move authentication redirects into their own file in
app/. - The shell knows details of a feature, such as the fields of a
CartItem. Move that knowledge back into the feature or into a contract.
A healthy shell reads like a table of contents. Every line names a feature and connects it to something.
Exercise
You add a notifications feature with a badge that must show the cart's item count. It must not import the cart feature. List the files you would create or edit, and say which layer each one belongs to.
Show answer
Reuse the existing contract, since it already exposes itemCount. In features/notifications/, make the badge widget take a CartSummary parameter and import it from core/contracts/cart_summary.dart. Add a buildNotificationsRoutes({required CartSummary cart}) function if the feature has pages. In the app shell, edit app/router.dart to spread the new routes and pass deps.cartSummary. AppDependencies needs no change, because the adapter already exists. Neither feature imports the other; only the shell touches both.
Exercise
A teammate moves GoRouter(...) into App.build "to keep everything in one place". After this change, users report that adding an item to the cart sends them back to the catalog. Explain why and give the fix.
Show answer
Adding an item calls notifyListeners, which can rebuild widgets above the router. Each rebuild of App.build creates a new GoRouter with initialLocation: '/catalog', so navigation state is discarded. Create the router once, in main or in a State.initState, and pass it to App.