Sub topic 13
Checking Boundaries Automatically
This chapter assumes you have read the earlier chapters on dependency rules and on exposing a feature through a barrel file. You should know Dart imports, the export directive, and the lib/features/<name>/ layout. It also assumes you can run dart analyze and edit pubspec.yaml and analysis_options.yaml.
Why rules need a checker
Dependency rules written in a wiki page erode. A developer under deadline pressure adds one import from features/checkout into features/cart/data/, the code works, and review misses it. Ten such imports later, the features are tangled again.
A rule that nothing checks is a suggestion. This chapter shows how to turn the rules from earlier chapters into checks that fail a pull request.
The rules to enforce are:
- Code in one feature may import another feature only through that feature's barrel file, such as
cart/cart.dart. - Features never import from
app. corenever imports fromfeaturesorapp.- Inside a feature,
domainimports neitherdatanorpresentation. presentationdoes not importdatadirectly.
Choosing a mechanism
Several tools can enforce these rules. They differ in effort and strength.
| Mechanism | Catches | Cost | Weakness |
|---|---|---|---|
| Code review | Anything a reviewer notices | None to set up | Inconsistent, depends on attention |
| A test that scans imports | Any rule you can express as a path check | A small Dart file | Runs only with the test suite |
| A custom lint package | Violations as you type in the IDE | Higher setup and maintenance | Depends on analyzer plugin APIs that change |
| Separate packages | Illegal imports, because the dependency does not exist | Large structural change | Covered in the next chapter |
For most teams, an import-scanning test is the best first step. It needs no extra dependencies and runs in the CI job you already have. Add lint rules later if you want feedback inside the editor.
Built-in lints that help
Two standard lints from the Dart linter catch part of the problem without any custom code. Enable them in analysis_options.yaml:
include: package:flutter_lints/flutter.yaml
linter:
rules:
- always_use_package_imports
- avoid_relative_lib_importsalways_use_package_imports forces package: imports everywhere. This looks like a style choice, but it matters here. A relative import such as ../../cart/data/cart_dto.dart hides which feature it points to, and it is harder to scan reliably. With package imports, every import has the same shape: package:my_app/features/cart/....
avoid_relative_lib_imports stops code from importing a lib file through a ../lib/ path, which would bypass the package URI entirely.
If you adopt this rule, the examples from earlier chapters change slightly. Replace import '../domain/cart_item.dart'; with import 'package:my_app/features/cart/domain/cart_item.dart';. Replace my_app with your package name from pubspec.yaml.
Note that always_use_package_imports conflicts with the prefer_relative_imports lint. Enable only one of them.
A boundary test you can run today
The test below reads every .dart file under lib/, extracts its imports, and checks them against the rules. It uses only dart:io and package:test, so add test or use flutter_test, which re-exports the same test functions.
Save it as test/architecture/boundaries_test.dart. Run it from the project root, because it reads lib/ by relative path. It assumes the package is named my_app.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
const packageName = 'my_app';
final importPattern = RegExp(
r'''^\s*(?:import|export)\s+['"]package:''' +
packageName +
r'''/([^'"]+)['"]''',
multiLine: true,
);
class Violation {
Violation(this.file, this.import, this.rule);
final String file;
final String import;
final String rule;
@override
String toString() => '$file imports $import ($rule)';
}
/// Returns the feature name for a path like `features/cart/data/x.dart`,
/// or null if the path is not inside a feature.
String? featureOf(String libPath) {
final parts = libPath.split('/');
if (parts.length >= 3 && parts[0] == 'features') return parts[1];
return null;
}
/// Returns the layer name (data, domain, presentation) inside a feature.
String? layerOf(String libPath) {
final parts = libPath.split('/');
if (parts.length >= 4 && parts[0] == 'features') return parts[2];
return null;
}
List<Violation> check(String file, String source) {
final violations = <Violation>[];
final fromFeature = featureOf(file);
final fromLayer = layerOf(file);
for (final match in importPattern.allMatches(source)) {
final target = match.group(1)!;
final toFeature = featureOf(target);
final toLayer = layerOf(target);
if (file.startsWith('core/') &&
(target.startsWith('features/') || target.startsWith('app/'))) {
violations.add(Violation(file, target, 'core must not import features or app'));
}
if (fromFeature != null && target.startsWith('app/')) {
violations.add(Violation(file, target, 'features must not import app'));
}
if (fromFeature != null &&
toFeature != null &&
fromFeature != toFeature) {
final isBarrel = target == 'features/$toFeature/$toFeature.dart';
if (!isBarrel) {
violations.add(Violation(
file,
target,
'import $toFeature only through its barrel file',
));
}
}
if (fromFeature != null && fromFeature == toFeature) {
if (fromLayer == 'domain' && (toLayer == 'data' || toLayer == 'presentation')) {
violations.add(Violation(file, target, 'domain must not import data or presentation'));
}
if (fromLayer == 'presentation' && toLayer == 'data') {
violations.add(Violation(file, target, 'presentation must not import data'));
}
}
}
return violations;
}
void main() {
test('lib/ respects feature boundaries', () {
final libDir = Directory('lib');
final violations = <Violation>[];
for (final entity in libDir.listSync(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
final relative = entity.path
.replaceAll('\\', '/')
.substring('lib/'.length);
violations.addAll(check(relative, entity.readAsStringSync()));
}
expect(violations, isEmpty, reason: violations.join('\n'));
});
}How the test works
The regular expression matches both import and export lines that start with package:my_app/. It captures the path after the package name, such as features/cart/domain/cart_item.dart.
featureOf and layerOf turn a path into names by splitting on /. The check function then applies each rule. A failing run prints one line per violation, so the developer sees which file to fix and why.
Edge cases and limits
This approach is simple, and it has gaps you should know about.
- Relative imports are invisible. The regular expression only sees
package:imports. That is why you enablealways_use_package_imports. Without it,import '../../checkout/checkout_page.dart';passes silently. - Multi-line imports. An
importwith ashowclause split over several lines still matches, because the pattern only needs the start of the line up to the closing quote. - Conditional imports. A line such as
import 'package:my_app/a.dart' if (dart.library.io) 'package:my_app/b.dart';matches only the first URI. Check conditional imports by hand, or extend the pattern. - Comments. A commented line starting with
//does not match because the pattern requires the line to start with whitespace and thenimport. A block comment containing an import at line start would produce a false positive. This is rare. - Feature-owned routes and shell files. The rule that features cannot import
appapplies to everything underfeatures/. The app shell, underapp/, is free to import any barrel file.
Add that sanity test to the same main:
test('check flags a deep import into another feature', () {
final result = check(
'features/checkout/presentation/checkout_page.dart',
"import 'package:my_app/features/cart/data/cart_dto.dart';",
);
expect(result, hasLength(1));
});Allowing exceptions deliberately
Sometimes a violation is temporary, for example during a migration. Do not weaken the rule. Keep an explicit allowlist in the test so every exception is visible in code review.
const allowedExceptions = <String>{
'features/checkout/presentation/checkout_page.dart -> features/cart/data/cart_dto.dart',
};
bool isAllowed(Violation v) =>
allowedExceptions.contains('${v.file} -> ${v.import}');Filter with violations.where((v) => !isAllowed(v)) before the expect. Each entry should have a ticket or a comment explaining when it will be removed. The list should only shrink. A useful extra check fails the test when an allowlist entry no longer matches a real violation, so stale entries get deleted.
Running the check in CI
The test is part of the normal suite, so any CI step that runs flutter test runs it. To get a clearer failure signal, run it as its own step:
name: architecture
on: [pull_request]
jobs:
boundaries:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
channel: stable
- run: flutter pub get
- run: dart analyze --fatal-infos
- run: flutter test test/architecture/boundaries_test.dartMark this job as a required status check in your repository settings. Otherwise reviewers can still merge a red build.
Custom lint packages
If you want errors to appear in the editor as the developer types, a custom lint package is the next step. Packages such as custom_lint let you write rules that run inside the analyzer, and some community packages ship ready-made import rules driven by configuration.
Weigh these points before adopting one:
- The analyzer plugin ecosystem has changed several times. Check that the package supports your Dart SDK version before you commit to it.
- Rules written as lints must parse the AST, which is more work than scanning text.
- Editor feedback is faster, but CI is still required, because not every developer runs the plugin.
A reasonable path is to keep the test as the authority and add editor lints only if reviews keep catching the same mistakes.
Common errors
- Test passes but violations exist. Usually relative imports. Enable
always_use_package_importsand fix existing imports first. - Test fails on its own barrel file. A feature's barrel exports its own internals, which the cross-feature rule does not apply to, because both sides belong to the same feature. If you see this, check that
featureOfreturns the same name for both paths. - Test fails on generated files. Generated code such as
*.g.dartlives next to its source and follows the same layer. If a generator emits imports you do not control, skip those files in the loop withentity.path.endsWith('.g.dart'). - Package name mismatch. If
packageNamedoes not equal thenameinpubspec.yaml, the pattern matches nothing and the test passes vacuously. The sanity test above catches this.
Exercise
Your boundary test passes, but a developer has added import '../../cart/data/cart_dto.dart'; inside features/checkout/presentation/checkout_page.dart. Why did the test not catch it, and what two changes fix it?
Show answer
The test's regular expression only matches imports that start with package:my_app/, so relative imports are never examined. First, enable the always_use_package_imports lint in analysis_options.yaml so relative imports are reported by the analyzer. Second, convert the existing relative imports to package: form. A sanity test that feeds check a deliberately bad import also guards against the pattern silently matching nothing.
Exercise
A feature's domain folder imports a class from the same feature's data folder, and your team wants to allow it for two weeks during a refactor. How do you do that without deleting the rule?
Show answer
Add the exact file -> import pair to an allowedExceptions set in the test, with a comment naming the ticket and removal date, and filter violations through it before the assertion. The rule stays active for all other code, the exception is visible in review, and an extra check that fails on unused entries forces the exception to be removed once the refactor is done.