Feature-based
- Dart course
- Expert
- Lesson 32/47
- 5 min
Learn feature-based architecture.
Feature-based
Feature-based structure organizes code by feature, not by layer. Each feature folder holds its own models, services and UI.
Example: lib/features/auth/ contains login_page.dart, auth_service.dart, user_model.dart together. Other features cannot use its contents directly unless the feature exports them.
Advantage: deleting or moving a feature is contained in one folder. Cross-feature coupling drops; team work gets easier. Each feature also holds its own tests.
Feature isolation
Features talk to each other through well-defined interfaces, not direct imports. This means changing one feature's internals does not affect others.
Example: the cart feature uses the AuthService interface of the auth feature, not its internal implementation. This makes rewriting auth safe.
Well-isolated features are portable and testable. Extracting a feature into a separate package also gets easier; it can be reused in other projects.
Practice Define a Feature class
Define a Feature class with final String name; final List<String> files; Feature(this.name, this.files); String describe() => 'feature: $name (${files.length} files)';. In main create final auth = Feature('auth', ['login_page.dart', 'auth_service.dart']); and add print(auth.describe());.
Starter code
void main() {
// define a Feature class (name, files fields; describe method)
// create an auth feature; print via describe
}Sample solution
class Feature {
final String name;
final List<String> files;
Feature(this.name, this.files);
String describe() => 'feature: $name (${files.length} files)';
}
void main() {
final auth = Feature('auth', ['login_page.dart', 'auth_service.dart']);
print(auth.describe());
}Expected output
feature: auth (2 files)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Feature import
import 'features/____/auth_service.dart';
import 'features/auth/auth_service.dart';
Explanation: the auth feature lives in its own folder.
2 What does each folder contain in a feature-based structure?
- Its own model, service and UI Correct answer
- Only models
- Only tests
- Only config files
Explanation: each feature folder keeps all its parts together.
3 Match the feature parts
| Term | Meaning |
|---|---|
features/auth |
Auth feature |
features/cart |
Cart feature |
auth_service.dart |
Service file |
login_page.dart |
UI file |