Show Flutter Navigation stack

Viewed 17373

I want to see the navigation stack in Flutter. Is it possible to use the Navigator class to print the navigation stack and other meta info about what's inside the Navigator?

Printing the Navigator with the print() method just gives the Navigator as a string.

Expected result: Navigator : { params...., params.... }

3 Answers

I think the only way you could do this currently is to override the Navigator class and keep track of the Routes yourself.

If you look at the Navigator source code there is a variable called _history which contains all the navigated routes but there's no way to access it unfortunately.

Perhaps the Navigator's observers parameter could help you? Though it would involve manually keeping track of the internal stack state of the Navigator. You could then operate on the routeStack member as necessary.

...
Navigator(
    observers: [MyNavigatorObserver()],
    onGenerateRoute: ...,
  )
...


class MyNavigatorObserver extends NavigatorObserver {
  List<Route<dynamic>> routeStack = List();

  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    routeStack.add(route);
  }

  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    routeStack.removeLast();
  }

  @override
  void didRemove(Route route, Route previousRoute) {
    routeStack.removeLast();
  }

  @override
  void didReplace({Route newRoute, Route oldRoute}) {
    routeStack.removeLast();
    routeStack.add(newRoute);
  }
}

If you're willing to use a library, try Fluro. On the router object, it provides printTree() method to print the navigation tree.

Related