Sub topic 14
Moving features into separate packages
What this chapter assumes
You should already know the feature folder layout from earlier chapters: data, domain, and presentation inside each feature, a barrel file as the public API, and dependency rules that keep features from importing each other's internals. You should also be comfortable reading a pubspec.yaml and know what a path dependency is.
So far those rules were enforced by conventions and lint checks. A Dart package makes the compiler and the package resolver enforce them. This chapter covers when that is worth the cost, how to do it, and what usually goes wrong.
Why a package changes the rules
In a single-package app, any file can import any other file under lib/. The barrel file is a convention, and a tired developer can bypass it with one relative import.
A package boundary is stricter in three ways:
- Declared dependencies. A package can import only packages listed in its own
pubspec.yaml. Ifshop_checkoutdoes not listshop_cart,import 'package:shop_cart/shop_cart.dart'fails to resolve. - No cycles. Pub rejects circular dependencies between packages, so a cycle between two features cannot be merged.
- A real public surface. Files under
lib/src/are private by Dart convention. Importingpackage:shop_cart/src/...from another package triggers theimplementation_importslint when you enable it.
A package also gives you isolated test runs, because flutter test inside one package builds and runs only that package's tests. Ownership also gets clearer, because a team can own packages/shop_cart and use code-owner rules on that path.
Target layout
The feature folders become packages. The app package keeps only the shell: main.dart, the router, and dependency wiring.
shop/
pubspec.yaml # workspace root
app/
pubspec.yaml
lib/
main.dart
router.dart
packages/
shop_core/
pubspec.yaml
lib/
shop_core.dart
src/
shop_cart/
pubspec.yaml
lib/
shop_cart.dart
src/
data/
domain/
presentation/
test/
shop_catalog/
pubspec.yaml
lib/
shop_catalog.dart
src/
test/Two changes from the folder version:
- The barrel file moves to
lib/<package_name>.dart. This is the file other packages import. - Everything else moves under
lib/src/. Your olddata,domain, andpresentationfolders keep their internal structure, just one level deeper.
The test folder moves inside the package, so the "tests mirror features" rule now holds automatically.
Setting up a pub workspace
Since Dart 3.6, pub workspaces let several packages share one dependency resolution and one pubspec.lock. Without a workspace, every package resolves versions on its own, and you can end up with different versions of go_router in different packages. Use a workspace unless you have a reason not to.
The root pubspec.yaml lists the members:
name: shop_workspace
publish_to: none
environment:
sdk: ^3.6.0
workspace:
- app
- packages/shop_core
- packages/shop_cart
- packages/shop_catalogEach member opts in with resolution: workspace. This is the cart package:
name: shop_cart
publish_to: none
environment:
sdk: ^3.6.0
resolution: workspace
dependencies:
flutter:
sdk: flutter
go_router: ^14.0.0
shop_core:
path: ../shop_core
dev_dependencies:
flutter_test:
sdk: flutterWorkspace membership does not replace path dependencies. shop_cart still has to declare shop_core explicitly. That declaration is the point: the list of path entries in each pubspec.yaml is the dependency graph of your app.
The app package depends on every feature:
name: shop_app
publish_to: none
environment:
sdk: ^3.6.0
resolution: workspace
dependencies:
flutter:
sdk: flutter
go_router: ^14.0.0
shop_core:
path: ../packages/shop_core
shop_cart:
path: ../packages/shop_cart
shop_catalog:
path: ../packages/shop_catalogRun flutter pub get once from any member directory or from the root. It resolves the whole workspace.
The barrel file becomes the package entry point
The barrel from the folder-based structure moves almost unchanged. Routes are still part of the public API, and the repository interface is exported while its implementation can stay private.
// packages/shop_cart/lib/shop_cart.dart
// Public API of the shop_cart package.
export 'src/cart_routes.dart' show cartRoutes;
export 'src/domain/cart_item.dart';
export 'src/domain/cart_repository.dart';
export 'src/cart_summary_adapter.dart' show CartSummaryAdapter;Use show on exports. It makes the public surface explicit and prevents a helper added later to a file from becoming public by accident.
The app shell imports only that file:
// app/lib/router.dart
import 'package:go_router/go_router.dart';
import 'package:shop_cart/shop_cart.dart';
import 'package:shop_catalog/shop_catalog.dart';
final router = GoRouter(
routes: [
...catalogRoutes,
...cartRoutes,
],
);Nothing else in app/ should import package:shop_cart/src/.... Turn on the lint in analysis_options.yaml so a violation shows up in the analyzer:
include: package:flutter_lints/flutter.yaml
linter:
rules:
implementation_imports: trueCross-feature contracts need a home
In the folder-based version, CartSummary lived in core/contracts. With packages it lives in shop_core, and both sides depend on that package instead of on each other.
// packages/shop_core/lib/shop_core.dart
export 'src/contracts/cart_summary.dart';
// packages/shop_core/lib/src/contracts/cart_summary.dart
abstract interface class CartSummary {
int get itemCount;
}The cart package implements the contract. The app shell creates the adapter and gives it to checkout:
// packages/shop_cart/lib/src/cart_summary_adapter.dart
import 'package:shop_core/shop_core.dart';
import 'domain/cart_repository.dart';
class CartSummaryAdapter implements CartSummary {
CartSummaryAdapter(this._repository);
final CartRepository _repository;
var _count = 0;
Future<void> refresh() async {
_count = (await _repository.loadItems()).length;
}
@override
int get itemCount => _count;
}shop_checkout lists shop_core in its dependencies and never lists shop_cart. If a developer adds a cart import to checkout, the analyzer reports the missing dependency (depend_on_referenced_packages), and the build fails when resolution cannot find the package.
What belongs in `shop_core`
The risk of this layout is a shop_core package that grows into a dumping ground. Every feature depends on it, so a change there rebuilds and retests everything.
Keep shop_core small and stable:
- Belongs: contract interfaces, design tokens and base widgets, the HTTP client wrapper, shared error types.
- Does not belong: anything only two features use. Either keep it in one of them and expose it through its barrel, or create a second small package (for example
shop_moneyfor currency formatting).
Several narrow shared packages cost more to maintain than one wide one, but they limit how much code each change touches. Split when the churn in shop_core starts to hurt.
Day-to-day commands
In a workspace, you test a package from its own directory:
cd packages/shop_cart
flutter testTo run every package's tests, loop over them in a script or use a tool such as Melos, which understands pub workspaces and can run a command across all members. Melos is optional. A shell loop is enough for a small number of packages.
In CI, run tests only for packages whose files changed, plus every package that depends on them. Computing "depends on" from the pubspec.yaml files is the main benefit of having explicit dependencies.
Problems you will hit
- Assets. An asset declared in a package is addressed as
packages/shop_cart/assets/empty_cart.png. WithImage.asset, passpackage: 'shop_cart'. Declare the asset in the package's ownpubspec.yaml. - Code generation. Tools such as
build_runnerrun per package. Generated files (*.g.dart) must be generated in the package that declares the annotations, and your CI must run generation for each package. - Localization. Each package can generate its own localization delegate. The app must register every delegate in
localizationsDelegates, or the strings will not load. - Dependency injection. Packages cannot reach into the app to find their dependencies. The app shell constructs repositories and passes them in, through constructors or through providers that the package exposes.
- Tests for the shell. The app package tests wiring: that every route resolves and that adapters are connected. Feature behavior is tested inside the feature package.
- Versions. Without a workspace, a package can silently lock an older
go_routerthan the app does. Workspaces prevent this. Mixed workspace and non-workspace members make resolution confusing, so migrate all or none.
Deciding when to split
| Signal | Suggests packages |
|---|---|
| Folder-boundary violations keep appearing despite lint rules | Yes |
| Different teams own different features | Yes |
| Full test run is too slow and most changes touch one feature | Yes |
| A feature will be reused in a second app | Yes |
| One small team, fewer than five features | Probably not yet |
| Feature boundaries still shift every sprint | Not yet |
Moving one feature
- Create
packages/shop_cartwith apubspec.yamland add it to the workspace list. - Move
lib/features/cartintopackages/shop_cart/lib/src, and move its tests intopackages/shop_cart/test. - Create
lib/shop_cart.dartfrom the old barrel, withshowclauses. - Add
shop_cartto the app's dependencies and replace everyfeatures/cart/...import withpackage:shop_cart/shop_cart.dart. - Fix anything that imported a cart internal. That is a boundary leak the folder structure had hidden. Replace it with a contract in
shop_coreor by exporting the symbol deliberately. - Run
flutter pub get,flutter analyze, and the tests in both packages.
Do one feature per pull request, starting with a leaf feature that no other feature depends on. Leaves have the fewest leaks to fix.
Exercise
Your shop_checkout package needs the number of items in the cart. A teammate adds shop_cart: path: ../shop_cart to checkout's pubspec.yaml. Two weeks later, cart needs to read the user's saved delivery address, which is owned by checkout, and the same teammate adds shop_checkout to cart's dependencies. What happens, and what is the better design?
Show answer
Pub rejects the second change because shop_cart and shop_checkout would depend on each other, which is a cycle. The better design is to remove checkout's dependency on cart. Put a CartSummary interface in shop_core, have cart implement it, and have the app shell pass the adapter to checkout. Do the same for the address: define an interface in shop_core (or have the app pass the address in), so neither feature package depends on the other.
Exercise
Why do you write export 'src/cart_routes.dart' show cartRoutes; instead of export 'src/cart_routes.dart'; in the package barrel?
Show answer
A bare export makes every public name in that file part of the package's API, including helpers added later. With show, only cartRoutes is public, so the surface of the package changes only when someone edits the barrel on purpose.