One added bonus of using the bloc library is that we can have access to all Changes
in one place. Even though in this application we only have one Cubit
, it's fairly common in larger applications to have many Cubits
managing different parts of the application's state.
If we want to be able to do something in response to all Changes
we can simply create our own BlocObserver
.
class SimpleBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
print('${bloc.runtimeType} $change');
}
}Copy to clipboardErrorCopied
Note: All we need to do is extend BlocObserver
and override the onChange
method.
In order to use the SimpleBlocObserver
, we just need to tweak the main
function:
void main() {
Bloc.observer = SimpleBlocObserver();
CounterCubit()
..increment()
..close();
}Copy to clipboardErrorCopied
The above snippet would then output:
Change { currentState: 0, nextState: 1 }
CounterCubit Change { currentState: 0, nextState: 1 }Copy to clipboardErrorCopied
Note: The internal onChange
override is called first, followed by onChange
in BlocObserver
.
💡 Tip: In BlocObserver
we have access to the Cubit
instance in addition to the Change
itself.