Bloc Listener:获取之前的状态

Bloc Listener : access to the previous state

我的 BlocListener 中有一行代码我想 运行 仅当满足先前状态的条件时。那么是否可以在 listener 中访问之前的状态,我知道我可以在 listenWhen 参数中访问它。

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());

您可以在状态每次更改时将状态添加到列表中,然后从列表中访问以前的状态。

我当然不能测试这个,因为我没有你的完整代码,但像这样的东西应该可以工作。

 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());
                    }

您要求的功能已内置。 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(),
)