flutterflutter-getxflutter-routes

Flutter GetX: How to obtain routes in stack, aka routing history?


I try to get access to the stack variable where GetX stores visited routes. It is purely educational for now, but I think it can be useful sometimes.

I tried Get.routeTree.routes but it is just a list of named routes. If there are no named routes it is empty.

I tried Get.keys.keys but it is always empty no matter how many routes were visited.

Currently, I am searching in getx/lib/get_navigation/src /extension_navigation.dart but without success.

Any ideas?


Solution

  • It looks like GetX uses Navigator internally, so the problem is not GetX-related.

    And the solution is simple: there is a package for that (surprise).

    So, this is how I did it.

    flutter pub add navigation_history_observer

    Add observer to GetMaterialApp:

     return GetMaterialApp(
           home: const FirstScreen(),
           initialRoute: Routes.FIRST_SCREEN,
           getPages: Routes.routes,
           navigatorObservers: [NavigationHistoryObserver()],
    

    NavigationHistory widget to add to every screen:

    class NavigationHistory extends StatelessWidget {
      const NavigationHistory({super.key});
    
      @override
      Widget build(BuildContext context) {
        return  Wrap(alignment: WrapAlignment.spaceBetween, children: [
                  const Text("Routes in stack: ", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  for (Route page in NavigationHistoryObserver().history) 
                  Text("${page.settings.name!}, ", style: 
                  TextStyle(fontSize: 20, fontWeight: FontWeight.bold, 
                             color: getColor(page.settings.name!)),)
                ]);
      }             
    }
    

    It works. This is what I see. Very useful while learning navigation API. enter image description here