Sub topic 4
Providing a Cubit with BlocProvider and reading it with context.read
This chapter assumes you can write a basic Cubit (Cubit<int> with emit), you know how BuildContext relates to the widget tree, and you know that InheritedWidget lets descendants look up data from an ancestor. By the end you will know how BlocProvider creates and disposes a Cubit, how descendants find it, and which errors show up when the lookup fails.
The problem BlocProvider solves
A Cubit is a plain Dart object. You could create one in a global variable, but then every screen depends on that global, tests cannot replace it, and nothing decides when it is closed. You could also pass it through constructors, but that gets tedious when the widget that needs the Cubit sits five levels below the widget that owns it.
BlocProvider is a widget that does three jobs:
- It creates a Cubit (or Bloc) and holds it.
- It makes that instance available to every widget below it in the tree.
- It closes the instance when the provider leaves the tree.
Under the hood it is built on the provider package's InheritedProvider. You do not need to know that to use it, but it explains why lookups go through BuildContext.
A complete example
This program runs as shown. It needs flutter_bloc in pubspec.yaml.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
void main() => runApp(const MaterialApp(home: CounterPage()));
class CounterPage extends StatelessWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: const CounterView(),
);
}
}
class CounterView extends StatelessWidget {
const CounterView({super.key});
@override
Widget build(BuildContext context) {
final count = context.watch<CounterCubit>().state;
return Scaffold(
body: Center(child: Text('$count')),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<CounterCubit>().increment(),
child: const Icon(Icons.add),
),
);
}
}The Page and View split is a common Bloc convention. CounterPage owns the provider. CounterView only consumes the Cubit. Because the context in CounterView.build sits below the provider, the lookup succeeds. The next chapter replaces context.watch with BlocBuilder, which narrows what rebuilds.
How the lookup works
context.read<CounterCubit>() walks up from the widget's context and returns the nearest ancestor BlocProvider<CounterCubit>. Three details follow from this.
- The type argument matters.
read<CounterCubit>()finds only a provider of exactly that type. If you wroteBlocProvider<Cubit<int>>, the lookup forCounterCubitwould fail. - "Nearest" wins. If two providers of the same type are nested, the inner one shadows the outer one for everything below the inner one.
- The search starts at the
contextyou pass in, and that context's own widget is not considered a provider for itself. This is the cause of the most common error, covered below.
read, watch, and select
The provider extensions on BuildContext come in three forms.
| Call | Subscribes to changes | Where it may be called | Typical use |
|---|---|---|---|
| `context.read<T>()` | No | Anywhere, including callbacks | Calling methods such as `increment()` |
| `context.watch<T>()` | Yes, rebuilds on every new state | Only inside `build` | Quick reads of state in small widgets |
| `context.select<T, R>((t) => ...)` | Yes, rebuilds only when the selected value changes | Only inside `build` | Reading one field of a large state |
context.read is equivalent to BlocProvider.of<T>(context). The listen: false default is what makes it safe in onPressed: it looks up the instance once and never registers the widget for rebuilds.
// Rebuilds only when the count's parity changes, not on every increment.
final isEven = context.select((CounterCubit c) => c.state.isEven);Use read for actions and watch or select for data. Avoid the reverse. Calling context.read<CounterCubit>().state inside build returns the current value but does not subscribe, so the UI will show a stale number after the next emit. This bug has no error message. The screen just stops updating.
Creation timing and ownership
Lazy by default
create runs the first time something reads the Cubit, not when the provider is built. For a Cubit that should start work immediately, you can either cascade a call or turn laziness off.
BlocProvider(
create: (_) => CounterCubit()..increment(),
lazy: false,
child: const CounterView(),
)With lazy: false the Cubit exists as soon as the provider is mounted. Leave the default in most cases. A Cubit nobody reads never runs its constructor, which avoids wasted network calls.
Automatic closing
When a provider created with create is removed from the tree, it calls close() on the Cubit. This releases the underlying stream controller and stops further emits. You do not call close yourself, and you should not close a provider-owned Cubit by hand.
BlocProvider.value for existing instances
BlocProvider.value provides an instance that someone else created. It does not close the instance. Use it when a new subtree, usually a new route, needs the Cubit that an earlier page already owns.
void openDetails(BuildContext context) {
final cubit = context.read<CounterCubit>();
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => BlocProvider.value(
value: cubit,
child: const CounterView(),
),
),
);
}A new route is pushed under the Navigator, which is usually above your page's provider. Without .value, the new page cannot see the Cubit.
Common errors
ProviderNotFoundException
The message reads "Error: Could not find the correct Provider<CounterCubit> above this Widget". It means the context you used has no matching provider among its ancestors. The usual cause is reading from the same build method that creates the provider:
// Broken: this context is ABOVE the BlocProvider.
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: ElevatedButton(
onPressed: () => context.read<CounterCubit>().increment(),
child: const Text('Add'),
),
);
}There are two fixes. The first is the Page/View split shown earlier. The second is a Builder, which gives the child its own context below the provider:
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: Builder(
builder: (innerContext) => ElevatedButton(
onPressed: () => innerContext.read<CounterCubit>().increment(),
child: const Text('Add'),
),
),
);
}The same error appears when a dialog or bottom sheet is opened with showDialog. Its route is built under the Navigator, not under your page, so the provider is not an ancestor. Pass the instance in with BlocProvider.value, as shown for routes.
Providing too high
Placing every Cubit at the top of MaterialApp makes lookups always succeed, but the Cubit then lives for the whole app and keeps its state after the user leaves the screen. Provide a Cubit as low as possible while still covering every widget that needs it. State that must survive across screens belongs higher. Per-screen state belongs at the screen.
Using a closed Cubit
Calling emit after close() throws a StateError. It can happen if an async method finishes after its provider was removed. Chapter 7 shows how to guard against that when modeling asynchronous work.
Summary of decisions
- Create the Cubit with
BlocProvider(create: ...)at the lowest widget that covers all users of it. - Call methods with
context.readand read state withcontext.watchorcontext.select. - Hand an existing instance to a new route or dialog with
BlocProvider.value. - Keep the provider and its consumers in separate widgets so the consumer's
contextis below the provider.
Exercise
A page builds BlocProvider(create: (_) => CounterCubit(), child: Text('${context.watch<CounterCubit>().state}')) inside its build method. It throws ProviderNotFoundException. Why, and how do you fix it without changing where the Cubit is created?
Show answer
The context used by context.watch belongs to the widget whose build method is running, which is above the BlocProvider it just created, so no provider is an ancestor of that context. Move the consumer into its own widget (for example a CounterView StatelessWidget) or wrap it in a Builder and use the builder's context. Either way the consumer's context is then below the provider.
Exercise
You push a new route from a page that owns a CounterCubit, and the new page throws ProviderNotFoundException when it reads the Cubit. What do you wrap the new page in, and why should you not use BlocProvider(create: ...) there?
Show answer
Wrap it in BlocProvider.value(value: context.read<CounterCubit>(), child: ...). The route sits under the Navigator, not under the original provider. Using create would build a second Cubit with separate state, and it would close that Cubit when the route is popped. .value shares the existing instance and leaves its closing to the original owner.