Created
December 15, 2025 00:32
-
-
Save kranfix/5506675ffa4013a734adc4ca60b34c25 to your computer and use it in GitHub Desktop.
Flutter's router observer to log the current stack of routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // route_stack_observer.dart | |
| import 'package:flutter/material.dart'; | |
| /// An observer that tracks the navigation stack and prints changes to the console. | |
| /// | |
| /// MaterialApp( | |
| /// navigatorObservers: [RouteStackObserver()], | |
| /// // ... rest of configuration | |
| /// ) | |
| /// | |
| /// | |
| /// Or, if you are using GoRouter: | |
| /// | |
| /// | |
| /// GoRouter( | |
| /// observers: [RouteStackObserver()], | |
| /// // ... rest of configuration | |
| /// ) | |
| /// | |
| class RouteStackObserver extends NavigatorObserver { | |
| static final List<Route<dynamic>> _routeStack = []; | |
| static List<String> get routeNames => _routeStack | |
| .map((route) => route.settings.name ?? 'unnamed') | |
| .toList(); | |
| static void printStack() x{ | |
| print('π Route Stack (${_routeStack.length} routes):'); | |
| for (var i = 0; i < _routeStack.length; i++) { | |
| final route = _routeStack[i]; | |
| final isFirst = i == 0; | |
| final isCurrent = i == _routeStack.length - 1; | |
| print(' ${isFirst ? 'π ' : isCurrent ? 'π' : ' '} $i: ${route.settings.name ?? 'unnamed'}'); | |
| } | |
| } | |
| @override | |
| void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { | |
| _routeStack.add(route); | |
| print('β Pushed: ${route.settings.name}'); | |
| printStack(); | |
| } | |
| @override | |
| void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { | |
| _routeStack.remove(route); | |
| print('β Popped: ${route.settings.name}'); | |
| printStack(); | |
| } | |
| @override | |
| void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { | |
| _routeStack.remove(route); | |
| print('ποΈ Removed: ${route.settings.name}'); | |
| printStack(); | |
| } | |
| @override | |
| void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) { | |
| if (oldRoute != null) _routeStack.remove(oldRoute); | |
| if (newRoute != null) _routeStack.add(newRoute); | |
| print('π Replaced: ${oldRoute?.settings.name} -> ${newRoute?.settings.name}'); | |
| printStack(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment