Sub topic 14
MultiBlocProvider, RepositoryProvider and bloc-to-bloc communication
Real apps have more than one Cubit and more than one data source. This chapter covers how to register many providers without deep nesting, how to share repositories, and how Cubits and Blocs can react to each other without becoming tangled.
Prerequisites
This chapter assumes you can already:
- Write a Cubit or Bloc and expose it with
BlocProvider. - Read it with
context.readandBlocBuilder. - Inject a repository through a constructor.
- Use Dart Streams (
listen,StreamSubscription).
Registering several providers
Each BlocProvider takes one child, so three Cubits means three levels of nesting. MultiBlocProvider takes a list and nests the providers for you. MultiRepositoryProvider does the same for repositories.
The list order matters. The first entry becomes the outermost provider, so later entries can read earlier ones through context inside their create callbacks. Entries cannot read ones that come after them.
The example below is one file. It registers two repositories and two Cubits, and one Cubit depends on the other's data source rather than on the other Cubit.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class AuthRepository {
Stream<bool> get signedIn;
Future<void> signOut();
}
class InMemoryAuthRepository implements AuthRepository {
final _controller = StreamController<bool>.broadcast();
@override
Stream<bool> get signedIn => _controller.stream;
@override
Future<void> signOut() async => _controller.add(false);
}
abstract class TodosRepository {
Future<List<String>> fetchTodos();
}
class InMemoryTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchTodos() async => ['Write tests', 'Ship feature'];
}
class SessionCubit extends Cubit<bool> {
SessionCubit(AuthRepository auth) : super(true) {
_subscription = auth.signedIn.listen(emit);
}
late final StreamSubscription<bool> _subscription;
@override
Future<void> close() async {
await _subscription.cancel();
return super.close();
}
}
class TodosCubit extends Cubit<List<String>> {
TodosCubit(this._todos, AuthRepository auth) : super(const []) {
_subscription = auth.signedIn.listen((signedIn) {
if (!signedIn) emit(const []);
});
}
final TodosRepository _todos;
late final StreamSubscription<bool> _subscription;
Future<void> load() async => emit(await _todos.fetchTodos());
@override
Future<void> close() async {
await _subscription.cancel();
return super.close();
}
}
void main() {
runApp(
App(
authRepository: InMemoryAuthRepository(),
todosRepository: InMemoryTodosRepository(),
),
);
}
class App extends StatelessWidget {
const App({
super.key,
required this.authRepository,
required this.todosRepository,
});
final AuthRepository authRepository;
final TodosRepository todosRepository;
@override
Widget build(BuildContext context) {
return MultiRepositoryProvider(
providers: [
RepositoryProvider<AuthRepository>.value(value: authRepository),
RepositoryProvider<TodosRepository>.value(value: todosRepository),
],
child: MultiBlocProvider(
providers: [
BlocProvider(
lazy: false,
create: (context) => SessionCubit(context.read<AuthRepository>()),
),
BlocProvider(
lazy: false,
create: (context) => TodosCubit(
context.read<TodosRepository>(),
context.read<AuthRepository>(),
)..load(),
),
],
child: const MaterialApp(home: HomePage()),
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<TodosCubit, List<String>>(
builder: (context, todos) => ListView(
children: [for (final t in todos) ListTile(title: Text(t))],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<AuthRepository>().signOut(),
child: const Icon(Icons.logout),
),
);
}
}Tapping the button asks the repository to sign out. The repository emits false on its stream, and TodosCubit clears its list in response. The two Cubits never reference each other.
RepositoryProvider
RepositoryProvider is a plain dependency-injection widget. It holds any object, not only a repository, and makes it available below it. It never rebuilds widgets, because a repository is not observable state. You read it with context.read<T>(), as in the create callbacks above.
There are two constructors:
RepositoryProvider(create: ...)builds the object the first time something reads it.RepositoryProvider.value(value: ...)exposes an object you built elsewhere, typically inmainso that it can be shared with code outside the widget tree.
RepositoryProvider does not call any close or dispose method on the object. If a repository owns a StreamController or a socket, close it yourself, in the place where you created it.
Provider lifetime: lazy, value and routes
Lazy creation
BlocProvider creates its Cubit lazily by default. The Cubit is built the first time a widget reads it, not when the provider is inserted. Usually that is what you want. It becomes a problem when the Cubit must start working on its own, such as SessionCubit above, which has to subscribe to the auth stream even if no widget has asked for it yet. Pass lazy: false in those cases. The example does this for both Cubits, so SessionCubit is subscribed from the first frame.
BlocProvider.value
BlocProvider(create: ...) owns the instance and closes it when the provider leaves the tree. BlocProvider.value only shares an existing instance and does not close it. Use .value to pass a Cubit to a subtree that lives outside the original provider's reach, most often a pushed route:
class TodoDetailPage extends StatelessWidget {
const TodoDetailPage({super.key});
@override
Widget build(BuildContext context) {
final count = context.select((TodosCubit c) => c.state.length);
return Scaffold(body: Center(child: Text('$count todos')));
}
}
void openDetail(BuildContext context) {
final cubit = context.read<TodosCubit>();
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => BlocProvider.value(
value: cubit,
child: const TodoDetailPage(),
),
),
);
}Do not use create: (_) => existingCubit for this. The new provider would then own the instance and close it when the route is popped, which breaks the original screen.
If the providers sit above MaterialApp, as in the example, every route can already see them and you do not need .value. You need it when a provider was added inside one page and a route pushed from that page must share it.
Bloc-to-bloc communication
Sooner or later one piece of state depends on another: clear the todos on sign-out, refresh a list when a filter changes. There are three common designs.
| Approach | How it works | Coupling | Use it when |
|---|---|---|---|
| Shared repository stream | Both Cubits subscribe to a stream exposed by a repository | Each depends on the repository only | The trigger is a domain event such as sign-out or a data change |
| `BlocListener` in the UI | A listener watches one Cubit and calls a method on another | The widget layer knows both | The reaction is tied to a screen, or involves navigation |
| Direct injection | Cubit A receives Cubit B and subscribes to `b.stream` | A depends on B's type | Rarely. Only for a tight, stable relationship |
The first approach is the one in the main example. It keeps the dependency arrows pointing at the data layer.
The second approach looks like this:
class SignOutTodosClearer extends StatelessWidget {
const SignOutTodosClearer({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return BlocListener<SessionCubit, bool>(
listenWhen: (previous, current) => previous && !current,
listener: (context, signedIn) => context.read<TodosCubit>().load(),
child: child,
);
}
}It is easy to follow, but the rule only runs while this widget is mounted. If the widget leaves the tree, the behavior silently stops. Business rules that must always apply belong in the repository or Cubit layer.
Subscriptions inside a Bloc
In a Bloc, prefer emit.onEach or emit.forEach inside an event handler over a manual listen. Both cancel automatically when the Bloc closes, and emitting is only allowed while the handler is active. With a manual subscription in a Cubit, as above, you must cancel it in close. If you forget, the Cubit stays alive and keeps emitting after the widget is gone.
Common errors
ProviderNotFoundException. Thecontextyou pass tocontext.readis above the provider. This happens when you create a provider and read it from the samebuildmethod. Move the reader into a child widget, or wrap it in aBuilder.- Wrong order in
MultiBlocProvider. A Cubit reads a provider listed after it and fails. Reorder the list so dependencies come first. - Cubit never reacts. A lazily created Cubit that only listens to a stream does not exist until something reads it. Use
lazy: false. - Closed Cubit on the previous screen. Passing an existing Cubit through
create:on a route makes the route own and close it. UseBlocProvider.value. - Circular dependency. Cubit A takes B and B takes A. Move the shared data into a repository that both depend on.
Exercise
In the example app, SessionCubit is registered with lazy: false. What goes wrong if you remove it, and nothing in the UI ever reads SessionCubit? Then name the approach from the table you would use if a pushed route needed TodosCubit and the providers were inside HomePage instead of above MaterialApp.
Show answer
Without lazy: false, SessionCubit is never created because nothing reads it, so its subscription to signedIn never starts and it never reacts to sign-out. For the pushed route, wrap the route's page in BlocProvider.value(value: cubit, ...) with the Cubit read from the outer context before the push, so the route shares the existing instance without closing it.
Exercise
A teammate makes TodosCubit take a SessionCubit in its constructor and listen to session.stream. Give two reasons to move this to a shared repository stream instead.
Show answer
Direct injection makes TodosCubit depend on another Cubit's type, so it cannot be tested without building a SessionCubit and it risks circular dependencies. A repository stream keeps each Cubit depending only on the data layer, so you can test each one by faking a single repository.