I'm relatively new to Flutter and the BLoC pattern, so I'm still trying to wrap my head around everything.
Let's say I have a quiz app where I have a BLoC called QuestionBloc
which uses a repository to fetch questions from a file.
Event on QuestionBloc
FetchQuestion
States on QuestionBloc
QuestionEmpty
QuestionLoading
QuestionLoaded
which contains a question objectQuestionError
I then have another BLoC called QuestionValidatorBloc
which is responsible for validating the answers to the question. The answer is entered into a text field and there is a submit button to trigger the validation.
Event on QuestionValidatorBloc
ValidateQuestion
States on QuestionValidatorBloc
ValidateInitial
ValidateInProgress
ValidateSuccess
ValidateError
This is fairly straight forward. However, now I need to incorporate both QuestionBloc
and QuestionValidatorBloc
into the same widget since one of them is responsible for fetching and displaying the question and the other for handling the validation action. How can I achieve this?
BlocListener is a Flutter widget that takes a BlocWidgetListener and an optional bloc and calls the listener when the state of the bloc changes. It should be used for functionality that only happens once per state change, such as navigation, displaying a SnackBar, displaying a dialog, and so on.
Bloc is a good pattern that will be suitable for almost all types of apps. It helps improve the code's quality and makes handling states in the app much more manageable. It might be challenging for someone who is just beginning to use Flutter because it uses advanced techniques like Stream and Reactive Programming.
A Cubit is similar to Bloc but has no notion of events and relies on methods to emit new states. Every Cubit requires an initial state which will be the state of the Cubit before emit has been called. The current state of a Cubit can be accessed via the state getter.
I assumed you are using the flutter_bloc
library. Let the QuestionBloc
listen to the QuestionValidatorBloc
using StreamSubscription
class QuestionBloc extends Bloc<QuestionEvent, QuestionState> {
QuestionValidatorBloc questionValidatorBloc;
StreamSubscription subscription;
MainPageBloc({@required this.questionValidatorBloc}) {
subscription= questionValidatorBloc.state.listen((state) {
if (state is ValidateSuccess) {
dispatch(YourEvent());
} else if(state is ValidateError{
dispatch(AnotherEvent());
}
});
}
...
Now you just have to pass the QuestionValidatorBloc
to the QuestionBloc
constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With