Sub topic 10
Injecting repositories and keeping data access out of the UI
This chapter assumes you know Dart classes, generics and async/await, and that you have written a Cubit with an immutable state class (see the earlier chapters on Cubit and on loading, success and failure states). Here you will move data access out of widgets and Cubits and into a repository, then hand that repository to the Cubit through its constructor.
Why data access does not belong in the UI
Suppose a widget calls http.get inside initState and calls setState with the result. That widget now knows the URL, the JSON shape, the error types and the retry rules. You cannot test the screen without a network. You cannot change the data source without editing the widget.
Putting the same call inside a Cubit is better, but it only moves the problem. A Cubit that builds its own HttpClient still depends on a concrete data source, so its tests need a real server.
The fix is to split the app into layers. Each layer talks only to the one below it.
| Layer | Knows about | Does not know about |
|---|---|---|
| Presentation (widgets) | Cubit state, Cubit methods | Repositories, HTTP, databases |
| Business logic (Cubit or Bloc) | Repository interface, state classes | Widgets, `BuildContext`, HTTP details |
| Repository | Data sources, mapping to domain types | Widgets, Cubits |
| Data source (API client, database) | Wire format, SQL, files | Everything above it |
The rule to remember is that the dependency arrows point downward. A repository never imports a Cubit, and a Cubit never imports a widget.
What a repository does
A repository is a class that hides where data comes from. It exposes methods in terms of your app's own types, such as Future<List<String>>, and it translates data source details into those types. It may combine several sources, for example a remote API and a local cache.
Typical responsibilities:
- Fetch and send data through one or more data sources.
- Convert raw responses (JSON maps, database rows) into domain objects.
- Convert low-level exceptions into errors the rest of the app understands.
- Decide caching rules, so the Cubit does not have to.
Declare the repository as an abstract class. The Cubit depends on the abstraction, and each implementation fills it in.
abstract class TodosRepository {
Future<List<String>> fetchTodos();
}
class InMemoryTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchTodos() async => ['Write tests', 'Ship feature'];
}A real implementation would take an API client in its constructor and parse the response. The Cubit would not change.
Constructor injection into a Cubit
Dependency injection means a class receives the objects it needs from outside instead of creating them itself. In Dart the simplest form is a constructor parameter.
import 'package:flutter_bloc/flutter_bloc.dart';
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 (e) {
emit(state.copyWith(
status: TodosStatus.failure,
errorMessage: e.toString(),
));
}
}
}This Cubit uses the TodosState and TodosStatus types from the earlier chapter on immutable state. Notice what is absent. There is no BuildContext, no http import and no SharedPreferences. The Cubit's whole world is the repository interface and its own state.
Three habits keep this clean:
- Store the repository in a private final field and never expose it.
- Catch exceptions in the Cubit and turn them into a failure state. The widget should never see a raw exception.
- Do not pass
BuildContextinto a Cubit. If a Cubit needs something from the widget tree, the widget should read it and pass it as a method argument.
Providing the repository with RepositoryProvider
Something has to create the repository and give it to the Cubit. RepositoryProvider is the widget for this. It works like BlocProvider, but for any object that is not a Cubit or Bloc. Descendants read the object with context.read<T>().
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return RepositoryProvider<TodosRepository>(
create: (_) => InMemoryTodosRepository(),
child: BlocProvider(
create: (context) =>
TodosCubit(context.read<TodosRepository>())..load(),
child: const MaterialApp(home: Scaffold()),
),
);
}
}Read it from the outside in:
RepositoryProvider<TodosRepository>creates anInMemoryTodosRepositorybut registers it under the abstract typeTodosRepository. Registering under the abstract type matters, becausecontext.read<TodosRepository>()looks up by the type argument you give it.- The
BlocProviderbelow it has acreatecallback that receives aBuildContext. That context sits under theRepositoryProvider, socontext.read<TodosRepository>()succeeds. ..load()is Dart's cascade operator. It builds the Cubit, callsload(), and still returns the Cubit. The data starts loading as soon as the Cubit is created.
The create callback of both providers runs lazily by default, on the first read. If you need the Cubit to start working before any widget reads it, pass lazy: false.
The repository is created once and shared by every Cubit below it. That is usually what you want, because a cache inside the repository then serves the whole subtree.
Where the repository comes from in a real app
In a larger app you usually create the repository once, near main, because it may need an already-initialized client or database. Use RepositoryProvider.value to supply an instance you built yourself.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
final repository = InMemoryTodosRepository();
runApp(TodosApp(repository: repository));
}
class TodosApp extends StatelessWidget {
const TodosApp({super.key, required this.repository});
final TodosRepository repository;
@override
Widget build(BuildContext context) {
return RepositoryProvider<TodosRepository>.value(
value: repository,
child: BlocProvider(
create: (context) =>
TodosCubit(context.read<TodosRepository>())..load(),
child: const MaterialApp(home: Scaffold()),
),
);
}
}This shape has a second benefit. TodosApp takes the repository as a parameter, so a widget test can pass a fake one.
What injection buys you
Because TodosCubit depends on the TodosRepository interface, you can replace the implementation without touching the Cubit.
- In production, pass a repository that calls your API.
- In a demo or an offline build, pass the in-memory one.
- In tests, pass a fake that returns a fixed list or throws on purpose.
Here is a failing fake and a check that the Cubit reports the failure state. It uses a plain async test with no extra packages, so you can see the mechanics. A later chapter shows the same idea with bloc_test.
import 'package:flutter_test/flutter_test.dart';
class FailingTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchTodos() async => throw Exception('offline');
}
void main() {
test('load emits failure when the repository throws', () async {
final cubit = TodosCubit(FailingTodosRepository());
await cubit.load();
expect(cubit.state.status, TodosStatus.failure);
expect(cubit.state.errorMessage, contains('offline'));
await cubit.close();
});
}No widget, no network and no timers are involved, so the test runs in milliseconds.
Common mistakes
- Creating the repository inside the Cubit. Writing
final _repository = HttpTodosRepository();as a field brings back the tight coupling you wanted to remove. Always take it as a constructor argument. - Depending on the concrete class. If the Cubit's constructor takes
InMemoryTodosRepository, you cannot swap in a fake. Depend on the abstract type. - Registering under the wrong type.
RepositoryProvider(create: (_) => InMemoryTodosRepository())without a type argument may infer the concrete type, and thencontext.read<TodosRepository>()fails. Write the type argument explicitly. - Calling
context.readinbuildto get values for display.readdoes not subscribe to changes. Repositories do not trigger rebuilds anyway, so display data should come from Cubit state. - Leaking data types upward. If the repository returns a raw
Map<String, dynamic>, every Cubit has to know the JSON shape. Return typed domain objects instead. - Letting widgets call the repository. It works, but it skips the Cubit and its state, so loading and error handling end up duplicated in the UI.
Exercise
A teammate writes class TodosCubit extends Cubit<TodosState> { TodosCubit() : super(const TodosState()); final _repo = HttpTodosRepository(); ... }. Name two problems this causes and show how to fix the constructor.
Show answer
First, the Cubit is tied to the concrete HttpTodosRepository, so tests cannot replace it with a fake and every test needs a real network. Second, the Cubit decides how its dependency is built, so switching to an in-memory or cached implementation means editing the Cubit. Fix: depend on the abstract TodosRepository and receive it through the constructor: TodosCubit(this._repository) : super(const TodosState()); final TodosRepository _repository;. Then create the repository outside, with RepositoryProvider<TodosRepository>, and read it in the BlocProvider with TodosCubit(context.read<TodosRepository>()).
Exercise
You wrap RepositoryProvider<TodosRepository> around the app, but your BlocProvider<TodosCubit> sits above it and calls context.read<TodosRepository>() in its create. What happens, and how do you fix it?
Show answer
The create callback receives a context that is not below the RepositoryProvider, so the lookup fails and throws a ProviderNotFoundException at runtime. Fix it by moving the BlocProvider inside the RepositoryProvider, so the repository is an ancestor of the context passed to create.