flutterflutter-navigationflutter-bottomnavigationflutter-alertdialogflutter-routes

pop until in flutter auto route package does not work


I am using the AutoRoute package for Flutter.

I have the following two screens generated using the auto route package,

HomeRoute()
ProductsRoute()

Then from HomeRouteI do the following,

context.router.push(const ProductsRoute());

Then inside the ProductRoute I call an API in the initState and if I an error occurs, I show a pop up that says Something went wrong!. Here,

I want to pop the alert, then pop the ProductsRoute() so that the user navigates back to the HomeRoute().

So using the AutoRoute I did the following,

context.router.popUntil((route) => route.settings.name == 'HomeRoute')

This did not work. It leads me to a white screen.

However it does work if I do context.route.pop() twice.

Can someone please tell me what I am doing wrong and how can I navigate back to the HomeRoute() using the Auto Route package?

Thanks.


Solution

  • I found the problem,

    With popUntil, if I want to go to the HomeRoute, I should not mention the HomeRoute. Instead I should mention the route on the stack that is after the HomeRoute. Then it started to work,

    For example suppose I have the following stack,

    ScreenA -> ScreenB -> ScreenC -> ScreenD

    Now if I want the user to show screen A by popping all the screens from screen D,

    I should do,

    context.router.popUntilRouteWithName(ScreenBRoute.name);   // <---- Should do
    

    NOT

    context.router.popUntilRouteWithName(ScreenARoute.name);   // <---- Should not do