Dart
Feature-based
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.
Exercise 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());.
Show example 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());
}
Test yourself
-
Feature import
import 'features/____/auth_service.dart';
Show answer
import 'features/auth/auth_service.dart';
-
What does each folder contain in a feature-based structure?
- Its own model, service and UI
- Only models
- Only tests
- Only config files
Show answer
Its own model, service and UI — each feature folder keeps all its parts together.
-
Match the feature parts
- features/auth
- Auth feature
- features/cart
- Cart feature
- auth_service.dart
- Service file
- login_page.dart
- UI file
Next lesson: Repository