bloc_presentation

Creator: coderz1093

Last updated:

0 purchases

bloc_presentation Image
bloc_presentation Images

Languages

Categories

Add to Cart

Description:

bloc presentation

bloc_presentation #


Extends blocs with an additional stream serving as a way of indicating
single-time events (so-called "presentation events").
Installation #
flutter pub add bloc_presentation
copied to clipboard
Usage #
First, create an event which will be emitted:
sealed class CommentCubitEvent {}

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

final String reason;
}
copied to clipboard
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
}
copied to clipboard
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 */);
}
}
copied to clipboard
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():
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(event.reason)));
}
},
child: MyWidget(),
)
copied to clipboard
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).
Example #
Here it is.
Usage with flutter_hooks #
Let's assume you have a cubit that emits presentation events:
class MyCubit extends Cubit<MyState> with BlocPresentationMixin {
(...)
}
copied to clipboard
You can listen to its events via the useOnStreamChange hook:
useOnStreamChange(
bloc.presentation,
(event) {
// Implement your listener here
},
)
copied to clipboard
Testing #
In order to to make testing of this package more straightforward, please, check out the bloc_presentation_test package.

License

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Customer Reviews

There are no reviews.