flutterblocflutter-bloc

Flutter - How to stop Bloc Listeners to run in the background stack


I am having a problem with my project. The problem is that I have when I push and go to another page and I run a BlocProvider to run a bloc function in that page, the BlocListener in the background stack also run, because it is the same bloc with the background bloc. How do I prevent the bloc listeners from the background stack/page to run?

The next page, to which I navigate, is a normal stateful widget class with a refresh indicator for fetching updated data. However, it seems that the same bloc function used on the home page to fetch initial data upon app opening or logging in is also invoked.

I have tried using the if(context.mount) in the function inside the bloc listeners in the background to stop them in case they are not in focus. but it is not working for me, the code inside the if condition still runs.

How can I prevent the bloc listeners from the background stack/page from running in this scenario?


Solution

  • I had a similar case some time ago, and the alternative solution is by play around with the route.

    You can determine whether context route is the top-most route on the navigator with isCurrent property from ModalRoute.

    Place it inside your listener code in background/home page as condition to prevent the code execution while the current page is blocked with other pages, modals or overlays.

    BlocListener(
      listener: (context, state) async {
        final route = ModalRoute.of(context);
        final isCurrentRoute = route?.isCurrent ?? false;
        if (isCurrentRoute) {
          // your listener code moved here
          // this code will run only if the 
          // current page is the top route
        }
      },
      child: ...,
    ),
    

    It's more cleaner than creating a page flag variable or refactoring the bloc itself.