Sub topic 9
Each feature owns its routes
This chapter assumes you can build a Flutter app with go_router, that you know how export works in Dart, and that your project already follows the feature folder layout from earlier chapters. The code uses go_router 7 or later, where path parameters are read with state.pathParameters.
The problem with one central route table
Many apps start with a single router file that imports every page and lists every route. In a small app this works. In a large one the file becomes a coordination point with three costs:
- Every feature's pages must be imported by
router.dart, so the app shell reaches intopresentation/folders it should not know about. - Every new screen in any feature edits the same file, which causes merge conflicts and makes ownership unclear.
- Deleting a feature means finding its routes scattered through a shared file.
The fix is to move the knowledge of a feature's routes into the feature. The feature exposes a list of routes. The app shell only combines the lists.
The ownership rule
A feature decides its own paths, the pages those paths show, and any redirects specific to it. The app shell decides which features are present and in what order. It does not know which page class a route builds.
The arrows show the dependency direction: the app depends on features, and features never import app/router.dart.
A feature's route file
Each feature has one routes file at its root, next to the barrel file. The file exports a List<RouteBase>. Here is the catalog feature, which has a list page and a detail page.
// lib/features/catalog/catalog_paths.dart
abstract final class CatalogPaths {
static const root = '/catalog';
static String detail(String productId) => '$root/$productId';
}// lib/features/catalog/catalog_routes.dart
import 'package:go_router/go_router.dart';
import 'catalog_paths.dart';
import 'presentation/catalog_page.dart';
import 'presentation/product_page.dart';
final catalogRoutes = <RouteBase>[
GoRoute(
path: CatalogPaths.root,
builder: (context, state) => const CatalogPage(),
routes: [
GoRoute(
path: ':productId',
builder: (context, state) {
final id = state.pathParameters['productId']!;
return ProductPage(productId: id);
},
),
],
),
];Three details are worth noting.
- The route file imports pages from
presentation/. This is allowed because it sits inside the feature. The app shell never needs those imports. - Child routes use relative paths (
':productId', no leading slash).go_routerjoins them to the parent, giving/catalog/:productId. - Path strings live in a small
CatalogPathsclass. The route table and any code that navigates to the feature share one definition, so they cannot drift apart.
Combining routes in the app shell
The app shell imports each feature's barrel file and spreads the lists into one router.
// lib/features/catalog/catalog.dart
export 'catalog_paths.dart';
export 'catalog_routes.dart';// lib/app/router.dart
import 'package:go_router/go_router.dart';
import '../features/cart/cart.dart';
import '../features/catalog/catalog.dart';
final router = GoRouter(
initialLocation: CatalogPaths.root,
routes: [
...catalogRoutes,
...cartRoutes,
],
);// lib/app/app.dart
import 'package:flutter/material.dart';
import 'router.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}Adding a third feature means one new import and one new spread line. Nothing inside the other features changes.
What the barrel file should export
The barrel file exports routes and paths. It does not need to export page widgets. If CartPage stays out of the barrel, no other feature can push it directly with Navigator.push(MaterialPageRoute(builder: (_) => CartPage())). They have to go through a path, which keeps the page class free to change.
// Another feature navigating to the cart through its public API
import 'package:go_router/go_router.dart';
import '../../cart/cart.dart';
void openCart(BuildContext context) => context.go(CartPaths.root);This snippet assumes cart.dart exports a CartPaths class like the catalog one. A navigation call that needs only a string is a lighter coupling than a widget import. When a target needs more than a path, the cross-feature chapter shows how to pass it through a shared contract.
Avoiding path collisions
go_router matches top-level routes in list order, and the first match wins. If two features both register /profile, the one earlier in the list silently shadows the other. Two habits prevent this:
- Start every feature's paths with a prefix that matches the feature name, such as
/catalogor/cart. - Keep paths in the feature's
Pathsclass so a search for a path string finds exactly one definition.
A feature that legitimately owns a top-level path, such as /login for an auth feature, is fine. The point is that exactly one feature owns it.
Redirects: feature-level and app-level
Redirects can live at two levels. Put each where its knowledge lives.
A feature-level redirect applies to that feature's routes and uses only that feature's rules. For example, the cart page can send the user back to the catalog when there is nothing to show:
import 'package:go_router/go_router.dart';
import 'presentation/cart_page.dart';
final cartRoutes = <RouteBase>[
GoRoute(
path: '/cart',
builder: (context, state) => const CartPage(),
redirect: (context, state) {
// Feature-specific rule: legacy links to /cart?empty=1 go to the catalog.
if (state.uri.queryParameters['empty'] == '1') return '/catalog';
return null; // null means "no redirect"
},
),
];An app-level redirect applies across features. Authentication is the usual case. The signed-in check depends on session state, which no single feature should own, so it belongs in app/router.dart:
// lib/app/router.dart (with an app-level guard)
import 'package:go_router/go_router.dart';
import '../features/cart/cart.dart';
import '../features/catalog/catalog.dart';
GoRouter buildRouter({required bool Function() isSignedIn}) {
return GoRouter(
initialLocation: CatalogPaths.root,
redirect: (context, state) {
final goingToLogin = state.matchedLocation == '/login';
if (!isSignedIn() && !goingToLogin) return '/login';
return null;
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) => const LoginPlaceholder(),
),
...catalogRoutes,
...cartRoutes,
],
);
}LoginPlaceholder stands in for the page of an auth feature. If you have one, spread ...authRoutes instead of defining the route inline.
A factory function like buildRouter has another advantage over a top-level final router: tests can build a router with a fake sign-in state or a different initialLocation.
Shell routes and shared chrome
Features often share a bottom navigation bar. The bar belongs to the app shell, but the routes inside it belong to features. With ShellRoute, the shell supplies the frame and the features supply the children:
// lib/app/router.dart (with a shell)
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../features/cart/cart.dart';
import '../features/catalog/catalog.dart';
final router = GoRouter(
initialLocation: CatalogPaths.root,
routes: [
ShellRoute(
builder: (context, state, child) => Scaffold(
body: child,
bottomNavigationBar: NavigationBar(
selectedIndex: state.matchedLocation.startsWith('/cart') ? 1 : 0,
onDestinationSelected: (i) =>
context.go(i == 0 ? CatalogPaths.root : '/cart'),
destinations: const [
NavigationDestination(icon: Icon(Icons.store), label: 'Catalog'),
NavigationDestination(icon: Icon(Icons.shopping_cart), label: 'Cart'),
],
),
),
routes: [
...catalogRoutes,
...cartRoutes,
],
),
],
);The feature route lists did not change. This is the payoff of the pattern: the same catalogRoutes works with or without a shell.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| A page from one feature appears at another feature's path | Two features register the same top-level path | Prefix paths with the feature name and keep one `Paths` class per feature |
| `GoException: no routes for location` | The feature's list was never spread into the router | Add `...featureRoutes` in `app/router.dart` |
| Child route never matches | The child path starts with `/`, so it is treated as absolute | Use a relative path such as `':productId'` for children |
| `router.dart` imports `presentation/` files | The route list was defined in the app instead of the feature | Move the `GoRoute` into the feature's routes file |
| Navigation code has string literals everywhere | No shared path definitions | Export a `Paths` class from the barrel file |
Summary of the pattern
- Each feature has
<feature>_routes.dartexporting aList<RouteBase>. - Each feature that others navigate to exports a
Pathsclass. - The barrel file exports routes and paths, not pages.
- The app shell spreads every list into one
GoRouterand handles cross-feature concerns: authentication redirects and shared navigation chrome.
Exercise
You add a profile feature. Its routes file defines GoRoute(path: '/cart/profile', ...) because the author wanted the page near the cart. After adding ...profileRoutes after ...cartRoutes in the router, opening /cart/profile shows nothing from the profile feature. Why can this happen, and what two changes fix it?
Show answer
The cart feature owns /cart, and go_router matches in list order, so the cart route (and any of its child routes) can take the location before the profile route is considered. The profile feature is claiming a path inside another feature's prefix. Fix it by giving the profile feature its own prefix, for example /profile, defined in a ProfilePaths class exported from profile.dart, so exactly one feature owns each path prefix. If the page truly belongs under the cart, register it as a child route inside the cart feature instead.
Exercise
The app needs to send signed-out users to /login for every feature. Should this redirect be written in each feature's routes file or in app/router.dart? Give one reason.
Show answer
In app/router.dart. The signed-in state is not owned by any single feature, and a single app-level redirect covers every feature, including features added later. Putting it in each feature would duplicate the rule and require every new feature to remember it.