Sub topic 10
Injecting repositories and keeping data access out of the UI
Assume you know Dart classes, interfaces, async/await, Flutter widgets, and the basic Cubit and BlocProvider APIs. This chapter uses dependency injection, which means giving an object the dependencies it needs instead of creating those dependencies inside the object.
Why use a repository?
A repository is a class that provides data to the rest of the application. It hides where that data comes from, such as an HTTP service, database, or in-memory cache.
The UI should describe what the user can see and do. It should not contain HTTP requests, JSON parsing, or database queries. A Cubit can ask a repository for data while remaining independent of the storage details.
Define the repository as an abstract class. An abstract class describes the operations without choosing an implementation.
abstract class TodosRepository {
Future<List<String>> fetchTodos();
}
class InMemoryTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchTodos() async {
return ['Write tests', 'Ship feature'];
}
}The Cubit receives the repository through its constructor. It does not create InMemoryTodosRepository itself.
import 'package:flutter_bloc/flutter_bloc.dart';
enum TodosStatus { initial, loading, success, failure }
class TodosState {
const TodosState({
this.status = TodosStatus.initial,
this.todos = const [],
this.errorMessage,
});
final TodosStatus status;
final List<String> todos;
final String? errorMessage;
TodosState copyWith({
TodosStatus? status,
List<String>? todos,
String? errorMessage,
}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
errorMessage: errorMessage ?? this.errorMessage,
);
}
}
class TodosCubit extends Cubit<TodosState> {
TodosCubit(this._repository) : super(const TodosState());
final TodosRepository _repository;
Future<void> load() async {
emit(state.copyWith(status: TodosStatus.loading));
try {
final todos = await _repository.fetchTodos();
emit(state.copyWith(
status: TodosStatus.success,
todos: todos,
));
} catch (error) {
emit(state.copyWith(
status: TodosStatus.failure,
errorMessage: error.toString(),
));
}
}
}Providing dependencies in the widget tree
RepositoryProvider makes a repository available to descendant widgets. The BlocProvider below it can read that repository and pass it to the Cubit.
RepositoryProvider<TodosRepository>(
create: (_) => InMemoryTodosRepository(),
child: BlocProvider(
create: (context) =>
TodosCubit(context.read<TodosRepository>())..load(),
child: const TodosPage(),
),
)context.read<TodosRepository>() retrieves the nearest repository of that type. The UI now only supplies the dependency and displays the Cubit's state. It does not know whether the data comes from memory, a server, or a database.
Benefits and common errors
Dependency injection makes implementations replaceable. A production app can use an API repository, while a test can use a fake repository that returns predictable data.
Common errors include:
- Creating the repository inside
TodosCubit, which prevents easy replacement. - Calling an API directly from a widget, which mixes presentation and data access.
- Registering a provider below the widget that tries to read it, which causes a provider lookup error.
- Exposing a concrete API client when the Cubit only needs the smaller repository interface.
Exercise
Why should TodosCubit receive a TodosRepository instead of creating InMemoryTodosRepository in its constructor?
Show answer
Injection keeps the Cubit independent of the data source, so production and test implementations can be substituted without changing the Cubit.