Complete the code to declare a repository interface in Flutter.
abstract class UserRepository { Future<List<User>> [1](); }
The method name getUsers clearly indicates fetching users, which is a common naming convention in repository interfaces.
Complete the code to implement the repository interface with a remote data source.
class RemoteUserRepository implements UserRepository { final ApiClient apiClient; RemoteUserRepository(this.apiClient); @override Future<List<User>> [1]() { return apiClient.fetchUsers(); } }
The method getUsers overrides the interface method and calls the API client to fetch users.
Fix the error in the repository method to handle exceptions properly.
Future<List<User>> getUsers() async {
try {
final users = await apiClient.fetchUsers();
return users;
} catch ([1]) {
throw Exception('Failed to load users');
}
}The variable e is commonly used to catch exceptions in Dart try-catch blocks.
Fill both blanks to create a repository that caches data locally after fetching remotely.
class CachedUserRepository implements UserRepository { final UserRepository remoteRepo; final UserCache cache; CachedUserRepository(this.remoteRepo, this.cache); @override Future<List<User>> getUsers() async { final cachedUsers = cache.[1](); if (cachedUsers != null) { return cachedUsers; } final users = await remoteRepo.[2](); cache.save(users); return users; } }
The cache method getCachedUsers retrieves stored users, and the remote repository method getUsers fetches fresh data.
Fill all three blanks to define a repository pattern with interface, implementation, and error handling.
abstract class [1] { Future<List<User>> getUsers(); } class [2] implements [1] { final ApiClient apiClient; [2](this.apiClient); @override Future<List<User>> getUsers() async { try { return await apiClient.fetchUsers(); } catch (e) { throw Exception('Error fetching users'); } } }
The interface is named UserRepository, and the implementation class is RemoteUserRepository which implements the interface and handles errors.