Sub topic 14
MultiBlocProvider, RepositoryProvider and bloc-to-bloc communication
Assume you know Dart classes, generics, async/await, Flutter widget lifecycles, and basic Bloc usage. This chapter shows how to compose several repositories and Blocs without constructing dependencies inside widgets.
A provider places an object in the widget tree. Descendants can retrieve that object with context.read<T>(). The provider does not make every descendant rebuild. Rebuilding still requires BlocBuilder, BlocSelector, or a listener.
Choosing the provider
| Provider | Responsibility | Typical use |
|---|---|---|
| `RepositoryProvider` | Exposes a data-access object | API client or repository |
| `BlocProvider` | Creates and exposes a Cubit or Bloc | Feature state |
| `MultiBlocProvider` | Groups several `BlocProvider` widgets | A page with multiple state objects |
MultiRepositoryProvider groups repository providers in the same way. Providers should be ordered so that a dependent object appears below the object it reads.
Composing repositories and Blocs
The following example creates one repository, two Cubits, and a listener that connects authentication to todos:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class TodosRepository {
Future<List<String>> fetchForUser();
}
class InMemoryTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchForUser() async {
return ['Review pull request', 'Write tests'];
}
}
class AuthCubit extends Cubit<bool> {
AuthCubit() : super(false);
void signIn() => emit(true);
void signOut() => emit(false);
}
class TodosCubit extends Cubit<List<String>> {
TodosCubit(this._repository) : super(const []);
final TodosRepository _repository;
Future<void> reload() async {
emit(await _repository.fetchForUser());
}
void clear() => emit(const []);
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return RepositoryProvider<TodosRepository>(
create: (_) => InMemoryTodosRepository(),
child: MultiBlocProvider(
providers: [
BlocProvider(create: (_) => AuthCubit()),
BlocProvider(
create: (context) =>
TodosCubit(context.read<TodosRepository>()),
),
],
child: const AuthToTodosListener(),
),
);
}
}
class AuthToTodosListener extends StatelessWidget {
const AuthToTodosListener({super.key});
@override
Widget build(BuildContext context) {
return BlocListener<AuthCubit, bool>(
listener: (context, signedIn) {
final todos = context.read<TodosCubit>();
if (signedIn) {
todos.reload();
} else {
todos.clear();
}
},
child: const MaterialApp(
home: Scaffold(
body: Center(child: Text('Todo screen')),
),
),
);
}
}TodosCubit reads the repository from the ancestor provider while it is being created. Flutter Bloc automatically closes a Bloc created by BlocProvider when that provider leaves the tree.
Connecting one Bloc to another
A BlocListener is often the clearest way to connect Blocs at the composition boundary. In the example, authentication changes trigger a todo reload or clear the current list.
This keeps AuthCubit independent from TodosCubit. It also avoids making one feature Bloc know the concrete type or lifecycle of another feature Bloc. The listener owns the coordination because the page owns both features.
You can also pass one Bloc into another constructor when the relationship is a genuine business rule. Use that approach when the receiving Bloc must react regardless of which screen displays it. Keep the dependency explicit and test it with a fake or mock.
Provider scope and common errors
A provider is visible only to descendants. Calling context.read<TodosRepository>() above its RepositoryProvider causes a ProviderNotFoundException. Similarly, a Bloc created in one route is unavailable after that route is removed.
Place app-wide providers above MaterialApp when many routes need them. Place feature providers near a feature when their state should be discarded when the feature closes.
Exercise
Why should the repository provider appear above the TodosCubit provider?
Show answer
TodosCubit reads TodosRepository during creation, so the repository must be an ancestor when the Cubit is constructed.