Reputation: 2430
There is one line of my code in my BlocListener
that I would like to run only if a condition on the previous state is met. So is it possible to get access to the previous state in the listener
, I know I can get access to it in the listenWhen
parameter.
BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
switch (state.status) {
case AuthenticationStatus.authenticated:
context.read<GetOffersCubit>().getOffersInMyArea();
context.read<GetRequestsCubit>().getRequestsInMyArea();
context.read<GetFavoritesCubit>().getFavorites();
PushNotificationsManager instanceNotificationManager = PushNotificationsManager();
instanceNotificationManager.init(state.user.id);
// this line should run only if previous.status != AuthenticationStatus.authenticated
context.read<NavigatorBloc>().add(GoToMainFrameScreen());
Upvotes: 1
Views: 6525
Reputation: 1186
The functionality you asked for is built in. Bloc documentation
BlocListener<BlocA, BlocAState>(
listenWhen: (previousState, currentState) {
//return true to invoke listener function
return true;
},
listener: (context, state) {
// do stuff here based on BlocA's state
},
child: Container(),
)
Upvotes: 2
Reputation: 5595
You could add the status to a list every time it changes then access the previous status from the list.
I can't test this of course because I don't have your full code but something like this should work.
List statusList = [];
BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
statusList.add(state.status); // adding to list before hitting switch/case
switch (state.status) {
case AuthenticationStatus.authenticated:
context.read<GetOffersCubit>().getOffersInMyArea();
context.read<GetRequestsCubit>().getRequestsInMyArea();
context.read<GetFavoritesCubit>().getFavorites();
PushNotificationsManager instanceNotificationManager = PushNotificationsManager();
instanceNotificationManager.init(state.user.id);
final previousStatusIndex = statusList.length - 1;
final previousStatus = statusList[previousStatusIndex];
// this line should run only if previous.status != AuthenticationStatus.authenticated
if (previousStatus != AuthenticationStatus.authenticated) {
context.read<NavigatorBloc>().add(GoToMainFrameScreen());
}
Upvotes: 1