Clean Architectureintermediate
Repository Pattern
Clean Architecture repository with abstract interface and implementation. Handles network/cache strategy.
#clean-architecture#repository#pattern
dart
| 1 | // Domain layer – abstract |
| 2 | abstract class UserRepository { |
| 3 | Future<Either<Failure, User>> getUser(String id); |
| 4 | Future<Either<Failure, List<User>>> getUsers(); |
| 5 | } |
| 6 | |
| 7 | // Data layer – implementation |
| 8 | class UserRepositoryImpl implements UserRepository { |
| 9 | final UserRemoteDataSource remoteDataSource; |
| 10 | final UserLocalDataSource localDataSource; |
| 11 | final NetworkInfo networkInfo; |
| 12 | |
| 13 | const UserRepositoryImpl({ |
| 14 | required this.remoteDataSource, |
| 15 | required this.localDataSource, |
| 16 | required this.networkInfo, |
| 17 | }); |
| 18 | |
| 19 | @override |
| 20 | Future<Either<Failure, User>> getUser(String id) async { |
| 21 | if (await networkInfo.isConnected) { |
| 22 | try { |
| 23 | final user = await remoteDataSource.getUser(id); |
| 24 | await localDataSource.cacheUser(user); |
| 25 | return Right(user.toDomain()); |
| 26 | } on ServerException catch (e) { |
| 27 | return Left(ServerFailure(e.message)); |
| 28 | } |
| 29 | } else { |
| 30 | try { |
| 31 | final user = await localDataSource.getCachedUser(id); |
| 32 | return Right(user.toDomain()); |
| 33 | } on CacheException { |
| 34 | return const Left(CacheFailure()); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | @override |
| 40 | Future<Either<Failure, List<User>>> getUsers() async { |
| 41 | // similar pattern... |
| 42 | throw UnimplementedError(); |
| 43 | } |
| 44 | } |