Flutter go_router, how to get the whole current stack of pages?
Asked Answered
F

4

11

Meaning if I go from a job screen to a client screen (the client the job was for), to another job screen (another job done for the client) etc, how can I display job > client > job?

And including parameters, so I could display Job 12 > SomeCompany > Job 17.

Sub routes aren't sufficient because the stack can repeat through multiple of the same pages infinitely.

Forepart answered 26/9, 2022 at 13:17 Comment(0)
B
9

I have found one solution which relies on the internal API implementation.
This might break in the future so use it with care.

GoRouter.of(context).routerDelegate.currentConfiguration.matches

Returns List<RouteMatch>

ⓘ Tip for Beginners

Make sure you have configured the routes correctly in GoRouter().
Hope they are nested as the route goes down the navigation instead of being siblings to each other.

Also, make sure that you give the whole URI location string to GoRouter.of(context).go() like '/home/level-2/level-3'

Bombay answered 8/5, 2023 at 12:43 Comment(0)
D
4

I'm not sure about checking the whole stack , but in case of anybody needed to check if there is a page on the stack , GoRouter has a canPop() method:

/// Returns `true` if there is more than 1 page on the stack. bool canPop() => GoRouter.of(this).canPop();

Divagate answered 17/10, 2022 at 13:36 Comment(0)
E
2

This isn't possible with go_router. auto_route has an API to check the stack, but go_router shows no search results for stack.


Instead of GoRouter.of like in this answer, you could use the extension method BuildContext#canPop. For example, in my onboarding page, I have this logic to pop if I can, and if not possible (the first time someone launches the app), I replace the page.:

if (context.canPop()) {
  context.pop();
} else {
  context.replace(Routes.dashboard);
  // Or alternatively, allow the user to navigate back to onboarding with:
  //  context.push(Routes.dashboard);
}
Elenoraelenore answered 17/11, 2022 at 21:10 Comment(0)
H
0

In your GoRouter, add a navigation observer GoNavigationObserver which extends the NavigationObserver.

override the didPush and didPop methods. And also have a class member as List<String> backStack. And you can always see the list of current Routes in the backStack.

class GoNavigationObserver extends NavigatorObserver {
    static List<String> backStack = [];
    
    @override
    void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
        backStack.add(route.settings.name ?? '');
    
        print(backStack.toString());
    }
    
    @override
    void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
        backStack.removeLast();
    
        print(backStack.toString());
    }
    
    @override
    String toString() {
        return backStack.toString();
    }
}
Heimer answered 26/9, 2023 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.