Skip to content

Instantly share code, notes, and snippets.

@Meghatronics
Last active May 17, 2023 09:41
Show Gist options
  • Select an option

  • Save Meghatronics/e4ffd10f09ffcad418ad3f5c85940f9b to your computer and use it in GitHub Desktop.

Select an option

Save Meghatronics/e4ffd10f09ffcad418ad3f5c85940f9b to your computer and use it in GitHub Desktop.
This adds a simple navigator observer to your flutter app, and prints activities of the nav in your debug console. Note that there are some more methods in `NavigatorObserver` that were not overridden. You may need to override them, depending on how you use the navigator, however this gist should is sufficient for most popular cases.
import 'dart:collection';
import 'package:flutter/widgets.dart';
class AppNavigatorObserver extends NavigatorObserver {
AppNavigatorObserver._();
static final instance = AppNavigatorObserver._();
final _stack = <Route>[];
UnmodifiableListView<Route> get currentStack => UnmodifiableListView(_stack);
UnmodifiableListView<String?> get currentStackRouteNames =>
UnmodifiableListView(_stack.map((e) => e.settings.name));
bool isCurrent(String routeName) {
final currentRoute = _stack.last;
assert(currentRoute.isCurrent);
return routeName == currentRoute.settings.name;
}
@override
void didPop(Route route, Route? previousRoute) {
debugPrint(
'Did Pop from ${route.settings.name} to ${previousRoute?.settings.name}',
);
assert(_stack.last == route);
_stack.removeLast();
assert(_stack.isEmpty || _stack.last == previousRoute);
}
@override
void didPush(Route route, Route? previousRoute) {
debugPrint(
'Did Push to ${route.settings.name} from ${previousRoute?.settings.name}',
);
assert(_stack.isEmpty || _stack.last == previousRoute);
_stack.add(route);
}
@override
void didReplace({Route? newRoute, Route? oldRoute}) {
debugPrint(
'Did Replace ${oldRoute?.settings.name} with ${newRoute?.settings.name}',
);
_stack.remove(oldRoute);
if (newRoute != null) _stack.add(newRoute);
}
@override
void didRemove(Route route, Route? previousRoute) {
debugPrint(
'Did Remove ${route.settings.name}',
);
_stack.remove(route);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: ThisApp._env.appName,
navigatorKey: AppNavigator.key,
navigatorObservers: [
AppNavigatorObserver.instance,
],
routes: AppRoutes.routes,
onGenerateRoute: AppRoutes.generateRoutes,
home: const SplashView(),
theme: ThemeData(
fontFamily: AppStyles.walsheimFontFamily,
extensions: [AppStyles(), AppColors()],
bottomSheetTheme: const BottomSheetThemeData(
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(40),
),
),
),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment