BlocProvider<B extends BlocBase<S>, S> class

BlocProvider

Similar to StateNotifierProvider but for BlocBase (Bloc and Cubit)

class CounterCubit extends Cubit<int> {
  CounterCubit(int state) : super(state);

  void increment() => emit(state + 1);
}

final counterProvider =
    BlocProvider<CounterCubit, int>((ref) => CounterCubit(0));

class MyHomePage extends ConsumerWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    // Rebuilds the widget if the cubit/bloc changes.
    // But does not rebuild if the state changes with the same cubit/bloc
    final counterCubit = watch(counterProvider.notifier);
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'initial counterCubit.state: ${counterCubit.state}',
            ),
            Consumer(builder: (context, watch, __) {
              // Rebuilds on every emitted state
              final _counter = watch(counterProvider);
              return Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              );
            }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read(counterProvider.notifier).increment(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

BlocProvider.notifier

Listen if the Bloc or Cubit when is recreated

Usasge:

Consumer(builder: (context, watch, __) {
  // Rebuilds if the cubit or bloc is recreated
  final _cubit = watch(counterProvider.notifier);
  return Text(
    '${_cubit.state}',
    style: Theme.of(context).textTheme.headline4,
  );
}),

BlocProvider.stream

Listen if the Bloc.stream or Cubit.stream

Usasge:

Consumer(builder: (context, watch, __) {
  // Rebuilds if the cubit or bloc is recreated
  final _cubit = watch(counterProvider.notifier);
  return Text(
    '${_cubit.state}',
    style: Theme.of(context).textTheme.headline4,
  );
}),

BlocProvider.overrideWithProvider

With pure dart:

final counterProvider = BlocProvider((ref) => CounterCubit(0));
final counterCubit = CounterCubit(3);
final counterProvider2 = BlocProvider((ref) => counterCubit);
final container = ProviderContainer(
  overrides: [
    counterProvider.overrideWithProvider(counterProvider2),
  ],
);

// reads `counterProvider2` and returns `counterCubit`
container.read(counterProvider.notifier);

// reads the `counterProvider2` `state` and returns `3`
container.read(counterProvider);

With Flutter:

final counterProvider = BlocProvider((ref) => CounterCubit(0));
final counterCubit = CounterCubit(3);
final counterProvider2 = BlocProvider((ref) => counterCubit);

ProviderScope(
  overrides: [
    counterProvider.overrideWithProvider(counterProvider2),
  ],
  child: Consumer(
    builder: (context, watch, _) {
      final countCubit = watch(counterProvider.notifier);
      return Container();
    },
  ),
);

BlocProvider.overrideWithValue

With pure dart:

final counterProvider = BlocProvider((ref) => CounterCubit(0));
final counterCubit = CounterCubit(3);
final container = ProviderContainer(
  overrides: [
    counterProvider.overrideWithValue(counterCubit),
  ],
);

// reads `counterProvider` and returns `counterCubit`
container.read(counterProvider.notifier);

// reads the `counterProvider.state` and returns `3`
container.read(counterProvider);

With Flutter:

final counterProvider = BlocProvider((ref) => CounterCubit(0));
final counterCubit = CounterCubit(3);

ProviderScope(
  overrides: [
    counterProvider.overrideWithValue(counterCubit),
  ],
  child: Consumer(
    builder: (context, watch, _) {
      final countCubit = watch(counterProvider.notifier);
      return Container();
    },
  ),
);

Auto Dispose

Marks the provider as automatically disposed when no-longer listened.

final counterProvider1 = BlocProvider.autoDispose((ref) => CounterCubit(0));

final counterProvider2 - AutoDisposeBlocProvider((ref) => CounterCubit(0));

The maintainState property is a boolean (false by default) that allows the provider to tell Riverpod if the state of the provider should be preserved even if no-longer listened.

final myProvider = BlocProvider.autoDispose((ref) {
  final asyncValue = ref.watch(myFutureProvider);
  final firstState = asyncValue.data!.value;
  ref.maintainState = true;
  return CounterBloc(firstState);
});

This way, if the asyncValue has no data, the provider won't create correctly the state and if the UI leaves the screen and re-enters it, the asyncValue will be readed again to retry creating the state.

Annotations
  • @sealed

Constructors

BlocProvider(Create<B, ProviderReference> create, {String? name})
BlocProvider

Properties

argument Object?
If this provider was created with the .family modifier, argument is variable used.
no setterinherited
debugId String
A unique identifier for this provider, used by devtools to differentiate providers
latefinalinherited
from → Family<dynamic, dynamic, dynamic, ProviderReference, RootProvider>?
If this provider was created with the .family modifier, from is the .family instance.
no setterinherited
hashCode int
The hash code for this object.
no setterinherited
name String?
A custom label for providers.
finalinherited
notifier → AlwaysAliveProviderBase<B, B>
BlocProvider.notifier
latefinal
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
stream → AlwaysAliveProviderBase<Stream<S>, AsyncValue<S>>
BlocProvider.stream
latefinal

Methods

create(ProviderReference ref) → B
createElement() → ProviderElement<B, S>
An internal method that defines how a provider behaves.
inherited
createState() → ProviderStateBase<B, S>
An internal method that creates the state of a provider.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
overrideWithProvider(BlocProvider<B, S> provider) → ProviderOverride
BlocProvider.overrideWithProvider
overrideWithValue(B value) → ProviderOverride
BlocProvider.overrideWithValue
inherited
select<Selected>(Selected selector(S value)) → ProviderListenable<Selected>
Partially listen to a provider.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Constants

autoDispose → const AutoDisposeBlocProviderBuilder
Auto Dispose