Sub topic 15
Migrating an existing app one feature at a time
This chapter assumes you know the layer-first and feature-first layouts from earlier chapters. It also assumes you are comfortable with Dart export directives and with the dependency rules: presentation depends on domain, data implements domain, and features reach each other only through a public file. The goal here is to move a real, working app to that structure without stopping feature work.
Why migrate in small steps
A single large "restructure" pull request touches hundreds of files. It conflicts with every open branch, it is hard to review, and a bug hidden inside it is hard to find. An incremental migration instead moves one feature per pull request. The app compiles and passes its tests after every merge, and you can stop at any point with a codebase that is better than before.
The cost is a period where two layouts exist side by side. Most of the techniques below exist to make that period safe and short.
Step 0: Prepare the ground
Do these before moving any file:
- Run the full test suite and record the result. You need a baseline to compare against.
- Add a few widget or integration tests for the flows you are about to move if they have none. Moving files should not change behavior, so tests are your proof.
- Agree on the target layout with the team. Use the
features/<name>/{data,domain,presentation}shape, the public barrel file, and thecore/folder. - Create the empty
lib/features/andlib/core/folders and merge that change alone.
A typical starting point looks like this:
lib/
main.dart
screens/
catalog_screen.dart
cart_screen.dart
checkout_screen.dart
models/
product.dart
cart_item.dart
services/
api_client.dart
cart_service.dart
widgets/
price_label.dart
product_tile.dartChoose the order of features
Not every feature is equally easy to move. Start with one that few other files import, and finish with the ones everything depends on.
| Candidate trait | Effect on migration | Guidance |
|---|---|---|
| Few inbound imports from other areas | Few call sites to update | Move first |
| Owns its own models and service | Its files move together | Good early candidate |
| Imported by many screens | Many import edits and merge conflicts | Move late |
| Shares models with several features | Forces a decision about shared code | Resolve the shared part first |
| Under heavy active development | High chance of conflicts | Coordinate timing with the team |
A small, self-contained feature such as settings or a profile screen is a good first move. It lets the team practice the routine on low-risk code. A central feature such as the cart is better after you have a working process.
Move one feature: the routine
The steps below move the cart feature. Each step ends with a compiling app.
- List the files that belong to the feature. Search for the feature's screens, models, services, and widgets. For the cart:
cart_screen.dart,cart_item.dart, andcart_service.dart. - Create the folders. Add
lib/features/cart/data,domain, andpresentation. - Move files with the IDE's move or refactor command, not by hand. The IDE rewrites imports in every file that references the moved one. Putting
cart_item.dartindomain/,cart_service.dartindata/andcart_screen.dartinpresentation/is a mechanical decision. - Split the service into an interface and an implementation. Old services often mix the contract with the HTTP or storage code. Put the abstract interface in
domain/and the concrete class indata/. - Add the barrel file
cart.dartthat exports only what other features may use. - Move the routes into
cart_routes.dartand spread them into the app router. - Run analysis and tests, then open the pull request.
Step 4 is the one that needs thought. After the split, presentation code depends on the interface:
// 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);
}
}If the old CartService already had a clean public surface, the interface is just that surface with the bodies removed. If it exposed internals such as raw JSON maps, use this move to hide them behind domain types.
Keep the old paths alive with shims
Moving a widely used file breaks every import of its old path. The IDE fixes imports it can see, but open branches still use the old path and will fail to compile after they merge.
A shim avoids that. Leave a one-line file at the old location that re-exports the new one:
// lib/models/cart_item.dart
// Deprecated: import 'package:shop_app/features/cart/cart.dart' instead.
export '../features/cart/domain/cart_item.dart';Old code keeps compiling. New code imports from the barrel. When no file imports the shim any more, delete it. A search for the old path tells you when that is.
The tutorial's example project is named shop_app here. Substitute your own package name.
Decide what is shared as you go
During a move you will find files that two features use, such as price_label.dart or api_client.dart. Resist the urge to settle everything up front. A practical rule:
- If the file is used by exactly one feature, move it into that feature.
- If it is used by several features and has no feature knowledge (a button, a formatter, an HTTP client), move it to
core/. - If it is used by several features because they share a business concept (a
Productmodel), pick an owner. Usually the feature that creates the data owns the model and exposes it through its barrel file. - If two features need each other's behavior, do not import across them. Define a small interface in
core/contracts/and let the app shell wire in an implementation, as in theCartSummaryexample from the cross-feature chapter.
Cycles are the main trap. If catalog imports cart and cart imports catalog, moving either one into its own folder makes the cycle visible and the analyzer cannot help you. Break the cycle first, in the old layout, by introducing the interface. Then move.
Stop the old layout from growing
A migration stalls when developers keep adding files to lib/screens because that is where they always went. Two cheap measures prevent this.
First, announce a rule: all new code goes into features/ or core/. Second, enforce a ratchet. The script below counts Dart files in the legacy folders and fails if the count rises above a recorded budget. Run it from the project root with dart run tool/legacy_check.dart, and store the starting number in tool/legacy_budget.txt.
// tool/legacy_check.dart
import 'dart:io';
const legacyDirs = [
'lib/screens',
'lib/models',
'lib/services',
'lib/widgets',
];
const budgetFile = 'tool/legacy_budget.txt';
int countDartFiles(String path) {
final dir = Directory(path);
if (!dir.existsSync()) return 0;
return dir
.listSync(recursive: true)
.whereType<File>()
.where((f) => f.path.endsWith('.dart'))
.length;
}
void main() {
final current =
legacyDirs.fold<int>(0, (sum, dir) => sum + countDartFiles(dir));
final budget = int.parse(File(budgetFile).readAsStringSync().trim());
if (current > budget) {
stderr.writeln('Legacy files grew from $budget to $current. '
'Put new code under lib/features or lib/core.');
exit(1);
}
if (current < budget) {
print('Legacy files dropped to $current. '
'Lower $budgetFile from $budget to $current.');
} else {
print('Legacy files unchanged at $current.');
}
}Shims count as legacy files, so the number only reaches zero when the shims are gone as well. Run this check in CI. Later, the boundary checks from the enforcement chapter replace it.
The migration loop
Common problems
- Merge conflicts on moved files. Git tracks renames by content similarity. Move files in a commit that changes nothing else, and make logic changes in a later commit. Tell the team which feature is moving this week.
- Tests left behind. Move tests with the feature into the mirrored
test/features/cart/...folders in the same pull request. Otherwise the test tree drifts from the source tree. - Generated code. Files produced by
build_runnerlive next to their sources. Move the source, delete the old generated files, and regenerate. Do not move generated files by hand. - Part files and relative imports. A
partdirective uses a relative path. Check that parts moved together with their parent library. - Barrel files exporting too much. It is tempting to export the whole folder to make errors go away. Export only what other features need, or the barrel file stops being a boundary.
- Moving everything into
core/. A largecore/is the oldutils/folder under a new name. Keep it for code with no feature knowledge.
Knowing when you are done
The migration is complete when the legacy folders are empty, no shims remain, and each feature is imported by others only through its barrel file. At that point, tighten the rules with automated boundary checks, and consider extracting stable features into packages if build times or team ownership call for it.
Exercise
You are migrating an app where CartScreen imports CatalogService, and CatalogScreen imports CartService to show a badge. Both live in lib/screens and lib/services. Which feature should you move first, and what must you do before moving it?
Show answer
First break the cycle while the files are still in the old layout. Define a small interface in shared code, for example a CartSummary with itemCount, have the cart side implement it, and make CatalogScreen depend on the interface instead of CartService. Then there is only one direction of dependency left (cart on catalog). Move the feature that is imported by fewer files first, and leave shims at the old paths so open branches keep compiling.
Exercise
The legacy file count is 42 and tool/legacy_budget.txt contains 42. A pull request moves the cart feature, leaves 3 shims in the old folders, and removes 7 other legacy files. What does legacy_check.dart report, and what should the author do?
Show answer
The move adds the new files under lib/features, which are not counted. The old folders lose 7 files and the 3 shims stay, so the count depends on whether the 3 shims replace files that were already counted. If the moved files were among the 7 removed and the shims are new, the count is 42 - 7 + 3 = 38. The script prints that legacy files dropped to 38, and the author lowers the budget file from 42 to 38 in the same pull request, so the ratchet keeps the gain.