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 counterCubitProvider =
    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, WidgetRef ref) {
    // Rebuilds the widget if the cubit/bloc changes.
    // But does not rebuild if the state changes with the same cubit/bloc
    final counterCubit = ref.watch(counterCubitProvider.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, ref, __) {
              // Rebuilds on every emitted state
              final _counter = ref.watch(counterCubitProvider);
              return Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              );
            }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ref.read(counterCubitProvider.notifier).increment();
        }
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

BlocProvider.notifier

BlocBase object getter, it can be either Bloc or Cubit.

Usage:

Consumer(builder: (context, ref, __) {
  return ElevatedButton(
    style: style,
    onPressed: () {
      ref.read(counterBlocProvider.notifier).increment();
    },
    child: const Text('Press me'),
  );
}),

BlocProvider.bloc

BlocBase object getter, it can be either Bloc or Cubit.

Usage:

Consumer(builder: (context, ref, __) {
  return ElevatedButton(
    style: style,
    onPressed: () {
      ref.read(counterBlocProvider.bloc).increment();
    },
    child: const Text('Press me'),
  );
}),

Creates a BlocProvider that needs to be overridden

With pure dart:

final blocProvider = BlocProvider<CounterBloc, int>.scoped('blocProvider');

final container = ProviderContainer(
  overrides: [
    blocProvider
        .overrideWithProvider(BlocProvider((ref) => CounterBloc(0))),
  ],
);

final counter = container.read(blocProvider); // counter = 0

With Flutter:

final blocProvider = BlocProvider<CounterBloc, int>.scoped('blocProvider');

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ProviderScope(
      overrides: [
        blocProvider
            .overrideWithProvider(BlocProvider((ref) => CounterBloc(0))),
      ],
      child: Consumer(
        builder: (context, ref, child) {
          final counter = ref.watch(blocProvider);  // counter = 0
          return Text('$counter');
        }
      )
    );
  }
}

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, ref, _) {
      final countCubit = ref.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, ref, _) {
      final countCubit = ref.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.

BlocProvider.when

For conditional rebuilds, you can use the when property.

ref.watch(
  counterBlocProvider
    .when((previous, current) => current > previous)),
);

ref.watch(
  blocProvider
    .when((prev, curr) => true)
    .select((state) => state.field),
  (field) { /* do something */ }
);

or for conditional listening:

ref.listen(
  counterBlocProvider
    .when((previous, current) => current > previous)),
);

ref.listen(
  blocProvider
    .when((prev, curr) => true)
    .select((state) => state.field),
  (field) { /* do something*/ }
);
Inheritance
Mixed in types
Available Extensions

Constructors

BlocProvider(B _createFn(BlocProviderRef<B, S> ref), {String? name, Iterable<ProviderOrFamily>? dependencies, @Deprecated('Will be removed in 3.0.0') Family<Object?>? from, @Deprecated('Will be removed in 3.0.0') Object? argument, @Deprecated('Will be removed in 3.0.0') DebugGetCreateSourceHash? debugGetCreateSourceHash})
Creates a StateNotifier and exposes its current state.
BlocProvider.internal(B _createFn(BlocProviderRef<B, S> ref), {required String? name, required Iterable<ProviderOrFamily>? dependencies, required Iterable<ProviderOrFamily>? allTransitiveDependencies, required DebugGetCreateSourceHash? debugGetCreateSourceHash, Family<Object?>? from, Object? argument})
An implementation detail of Riverpod
BlocProvider.scoped(String name)
Creates a BlocProvider that needs to be overridden

Properties

allTransitiveDependencies Iterable<ProviderOrFamily>?
All the dependencies of a provider and their dependencies too.
finalinherited
argument Object?
If this provider was created with the .family modifier, argument is the variable that was used.
finalinherited
bloc AlwaysAliveRefreshable<B>
Obtains the Bloc associated with this provider, without listening to state changes.
latefinal
debugGetCreateSourceHash → DebugGetCreateSourceHash?
A debug-only fucntion for obtaining a hash of the source code of the initialization function.
finalinherited
dependencies Iterable<ProviderOrFamily>?
The list of providers that this provider potentially depends on.
finalinherited
from Family<Object?>?
If this provider was created with the .family modifier, from is the .family instance.
finalinherited
hashCode int
The hash code for this object.
no setterinherited
name String?
A custom label for providers.
finalinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

addListener(Node node, void listener(S? previous, S next), {required void onError(Object error, StackTrace stackTrace)?, required void onDependencyMayHaveChanged()?, required bool fireImmediately}) ProviderSubscription<S>
Starts listening to this transformer
inherited
createElement() BlocProviderElement<B, S>
An internal method that defines how a provider behaves.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
overrideWith(Create<B, BlocProviderRef<B, S>> create) Override
read(Node node) → S
Obtains the result of this provider expression without adding listener.
inherited
select<Selected>(Selected selector(S value)) AlwaysAliveProviderListenable<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
Marks the provider as automatically disposed when no longer listened to.
family → const BlocProviderFamilyBuilder
A group of providers that builds their value from an external parameter.