Skip to content

Instantly share code, notes, and snippets.

@kranfix
Created December 15, 2025 00:32
Show Gist options
  • Select an option

  • Save kranfix/5506675ffa4013a734adc4ca60b34c25 to your computer and use it in GitHub Desktop.

Select an option

Save kranfix/5506675ffa4013a734adc4ca60b34c25 to your computer and use it in GitHub Desktop.
Flutter's router observer to log the current stack of routes
// 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