Repository Pattern
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 100 of 110.
The Repository pattern separates data access logic from business logic by creating an abstraction layer between your application and data sources. Instead of having your classes directly interact with databases, APIs, or files, they work with a repository that handles all data operations.
The pattern defines an interface for data operations, and concrete implementations handle the actual storage mechanism. This makes it easy to swap data sources without changing your business logic:
// Entity
class User {
final int id;
final String name;
User(this.id, this.name);
}
// Repository interface
abstract class UserRepository {
User? getById(int id);
List<User> getAll();
void save(User user);
void delete(int id);
}
// In-memory implementation
class InMemoryUserRepository implements UserRepository {
final Map<int, User> _users = {};
@override
User? getById(int id) => _users[id];
@override
List<User> getAll() => _users.values.toList();
@override
void save(User user) => _users[user.id] = user;
@override
void delete(int id) => _users.remove(id);
}
void main() {
UserRepository repo = InMemoryUserRepository();
repo.save(User(1, 'Alice'));
repo.save(User(2, 'Bob'));
print(repo.getById(1)?.name); // Alice
print(repo.getAll().length); // 2
}Your business logic depends only on the UserRepository interface. You could later create a DatabaseUserRepository or ApiUserRepository that implements the same interface, and swap implementations without modifying any code that uses the repository. This pattern is essential for testable, maintainable applications where data sources may change over time.
Challenge
EasyLet's build a product inventory system using the Repository pattern! You'll create an abstraction layer that separates how products are stored from how they're used, making it easy to swap storage implementations without changing business logic.
You'll organize your code into two files:
product_repository.dart: This file contains your entity and repository classes. Start with aProductclass that hasfinalfields forid(int),name(String), andprice(double). Then define an abstract classProductRepositorythat declares the contract for data operations:getById(int id)returning a nullableProduct,getAll()returning a list of products,save(Product product)to store a product, anddelete(int id)to remove one. Finally, create anInMemoryProductRepositorythat implements this interface using aMap<int, Product>for storage.main.dart: Import your repository file and demonstrate the Repository pattern in action. Create anInMemoryProductRepositorybut store it in a variable of typeProductRepository- this shows how your code depends on the interface, not the implementation. Save three products:Laptop(id: 1, price: 999.99),Mouse(id: 2, price: 29.99), andKeyboard(id: 3, price: 79.99). Then retrieve and print the product with id 2 in the formatFound: [name] - $[price]. Delete the product with id 1. Finally, print the count of remaining products asProducts in stock: [count].
The power of this pattern is that your main code only knows about the ProductRepository interface. You could later create a DatabaseProductRepository or ApiProductRepository and swap it in without changing any of the business logic!
Expected output:
Found: Mouse - $29.99
Products in stock: 2Cheat sheet
The Repository pattern separates data access logic from business logic by creating an abstraction layer between your application and data sources.
Define an interface for data operations:
// Entity
class User {
final int id;
final String name;
User(this.id, this.name);
}
// Repository interface
abstract class UserRepository {
User? getById(int id);
List<User> getAll();
void save(User user);
void delete(int id);
}Create concrete implementations that handle the actual storage mechanism:
// In-memory implementation
class InMemoryUserRepository implements UserRepository {
final Map<int, User> _users = {};
@override
User? getById(int id) => _users[id];
@override
List<User> getAll() => _users.values.toList();
@override
void save(User user) => _users[user.id] = user;
@override
void delete(int id) => _users.remove(id);
}Use the repository through its interface:
void main() {
UserRepository repo = InMemoryUserRepository();
repo.save(User(1, 'Alice'));
repo.save(User(2, 'Bob'));
print(repo.getById(1)?.name); // Alice
print(repo.getAll().length); // 2
}Business logic depends only on the interface, allowing you to swap implementations (e.g., DatabaseUserRepository, ApiUserRepository) without modifying code that uses the repository.
Try it yourself
import 'product_repository.dart';
void main() {
// Create repository - note the type is the interface, not the implementation
// TODO: Create an InMemoryProductRepository and store it in a ProductRepository variable
// TODO: Save three products:
// - Laptop (id: 1, price: 999.99)
// - Mouse (id: 2, price: 29.99)
// - Keyboard (id: 3, price: 79.99)
// TODO: Retrieve product with id 2 and print: "Found: [name] - $[price]"
// TODO: Delete product with id 1
// TODO: Print the count of remaining products: "Products in stock: [count]"
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor12Async OOP
Futures & async/awaitStreams BasicsStream ControllersAsync ConstructorsAsync in Class MethodsRecap - Data Fetcher15Design Patterns Part 2
Command PatternAdapter PatternDecorator PatternTemplate Method PatternState PatternComposite PatternRepository Pattern