D
ArchitectureEasy20 XP3 min read

What is the Repository pattern and why is it used in Flutter?

TL;DR: The Repository pattern abstracts data sources behind an interface. The domain/presentation layer talks only to the repository interface — it doesn't know if data comes from an API, local database, or a cache.

Full Answer

Without a repository, your BLoC or use case calls Dio directly. Swap Dio for GraphQL and you rewrite every BLoC. With a repository interface, you only change the implementation.

Pattern Components

  • Interface (abstract class): Defined in Domain — declares what operations exist
  • Implementation: In Data layer — does the actual Dio/Hive/SQLite work
  • Callers: Use cases or BLoC — depend only on the interface, not the impl
🎯

Test the use case with a FakeRepository (in-memory list). Test the repository implementation with a mock HTTP client. Never test both in the same test.

Code Examples

dartRepository interface and implementation
Output
// Use case calls QuestionsRepository (interface)
// Actual API + cache logic is hidden in the implementation

Common Mistakes

  • Putting caching logic in the use case — caching is a data-layer concern
  • Returning raw API models from the repository — always map to domain entities

Interview Tip

💡

The repository is the seam between 'what your app needs' (domain) and 'how it gets it' (data). Swappability and testability are its primary benefits.

#repository#abstraction#data-source#testability