bloc_presentation badge Build status

Extends blocs with an additional stream serving as a way of indicating single-time events (so-called "presentation events").


flutter pub add bloc_presentation


First, create an event which will be emitted:

sealed class CommentCubitEvent {}

class FailedToUpvote implements CommentCubitEvent {
  const FailedToUpvote(this.reason);

  final String reason;

Next, extend your Bloc/Cubit with the presentation mixin which will give you access to the emitPresentation method:

class CommentCubit extends Cubit<CommentState> with BlocPresentationMixin<CommentState, CommentCubitEvent> {
  // body

Now in your methods instead of emitting new state, you can emit a single-time presentation event without overwriting your Bloc/Cubit state:

void upvote() {
  // upvoting logic

  if (!success) {
    // we can emit it and forget about cleaning it from the state
    emitPresentation(const FailedToUpvote('bad connection'));
  } else {
    emit(/* new state */);

In this case above, we do not want to lose our Bloc/Cubit state after a non-fatal failure. Instead, we want to communicate this failure and not emit any new states. Then, in the UI code one can react to such events using BlocPresentationListener or useBlocPresentationListener:

BlocPresentationListener<CommentCubit, CommentCubitEvent>(
  listener: (context, event) {
    switch (event) {
      case FailedToUpvote():
          ..showSnackBar(SnackBar(content: Text(event.reason)));
  child: MyWidget(),

By default, CommentCubit will be looked up using package:provider in the widget tree. However, a bloc can be provided directly using the BlocPresentationListener.bloc parameter (analogous to how package:bloc listeners work).


Here it is.