Skip to content

Instantly share code, notes, and snippets.

@udit-raj-simform
Created May 24, 2023 07:57
Show Gist options
  • Save udit-raj-simform/cade9b8ad993b044661bb2fc28983b92 to your computer and use it in GitHub Desktop.
Save udit-raj-simform/cade9b8ad993b044661bb2fc28983b92 to your computer and use it in GitHub Desktop.
NavigatorMiddleware with RouteObserver
import 'package:lms_flutter_project/utils/exports.dart';
typedef OnRouteChange<R extends Route<dynamic>> = void Function(
R route, R previousRoute);
class NavigatorMiddleware<R extends Route<dynamic>> extends RouteObserver<R> {
NavigatorMiddleware({
this.enableLogger = true,
this.onPush,
this.onPop,
this.onReplace,
this.onRemove,
}) : _stack = [];
final List<R> _stack;
final bool enableLogger;
final OnRouteChange<R>? onPush;
final OnRouteChange<R>? onPop;
final OnRouteChange<R>? onReplace;
final OnRouteChange<R>? onRemove;
//create clone list from stack
List<R> get stack => List<R>.from(_stack);
@override
void didPush(Route route, Route? previousRoute) {
_logger('{didPush} \n route: $route \n previousRoute: $previousRoute');
_stack.add(route as R);
_logStack();
if (onPush != null) {
onPush!(route, previousRoute as R);
}
super.didPush(route, previousRoute);
}
@override
void didPop(Route route, Route? previousRoute) {
_logger('{didPop} \n route: $route \n previousRoute: $previousRoute');
_stack.remove(route);
_logStack();
if (onPop != null) {
onPop!(route as R, previousRoute as R);
}
super.didPop(route, previousRoute);
}
@override
void didReplace({Route? newRoute, Route? oldRoute}) {
_logger('{didReplace} \n newRoute: $newRoute \n oldRoute: $oldRoute');
if (_stack.contains(oldRoute)) {
final oldItemIndex = _stack.indexOf(oldRoute as R);
_stack[oldItemIndex] = newRoute as R;
}
_logStack();
if (onReplace != null) {
onReplace!(newRoute as R, oldRoute as R);
}
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
}
@override
void didRemove(Route route, Route? previousRoute) {
_logger('{didRemove} \n route: $route \n previousRoute: $previousRoute');
stack.remove(route);
_logStack();
if (onRemove != null) {
onRemove!(route as R, previousRoute as R);
}
super.didRemove(route, previousRoute);
}
@override
void didStartUserGesture(Route route, Route? previousRoute) {
_logger(
'{didStartUserGesture} \n route: $route \n previousRoute: $previousRoute');
super.didStartUserGesture(route, previousRoute);
}
@override
void didStopUserGesture() {
_logger('{didStopUserGesture}');
super.didStopUserGesture();
}
void _logStack() {
final mappedStack =
_stack.map((Route route) => route.settings.name).toList();
_logger('Navigator stack: $mappedStack');
}
void _logger(String content) {
if (enableLogger) {
log(content);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment