Clean architecture
- Dart course
- Expert
- Lesson 31/47
- 5 min
Learn clean architecture principles.
Clean architecture
Clean architecture separates code into layers: presentation, domain and data. Dependencies always flow inward — toward the domain layer.
The domain layer (Entity, Repository interface) depends on nothing. The data layer (DataSource) implements the domain interface. The presentation layer calls the domain, not the data directly.
This separation makes it easy to swap the data source (API, database, cache). In tests a mock repository is provided; the domain logic stays unchanged.
Layer separation
Three core layers: Entity (domain model, business logic), Repository (data access contract), DataSource (concrete data source).
The presentation layer calls a UseCase; the UseCase uses the repository; the repository reads from a DataSource. Each layer talks only to the next.
This chain prevents a single change from rippling through the system. For example, switching from API to database only changes the DataSource; domain and presentation stay intact.
Practice Define an Entity and a Repository
Define a UserEntity class with final String id; final String name; UserEntity(this.id, this.name);. Define an abstract class UserRepository with a UserEntity fetch(String id); method. In main create final user = UserEntity('1', 'Ayşe'); and add print(user.name);.
Starter code
void main() {
// define the UserEntity class (id, name fields)
// define an abstract UserRepository (fetch method)
// create a UserEntity; print name
}Sample solution
class UserEntity {
final String id;
final String name;
UserEntity(this.id, this.name);
}
abstract class UserRepository {
UserEntity fetch(String id);
}
void main() {
final user = UserEntity('1', 'Ayşe');
print(user.name);
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which way do dependencies flow in clean architecture?
- Outward
- Downward
- Upward
- Inward (toward domain) Correct answer
Explanation: dependencies always flow inward, toward the domain.
2 The Repository interface
____ class UserRepository {
UserEntity fetch(String id);
}
abstract class UserRepository {
UserEntity fetch(String id);
}
Explanation: abstract class defines a contract.
3 Match the layers
| Term | Meaning |
|---|---|
Entity |
Domain model |
Repository |
Data access contract |
DataSource |
Data source |
UseCase |
Business rule |