useRouteAware function

void useRouteAware({
  1. required RouteObserver<Route> observer,
  2. VoidCallback? onDidPopNext,
  3. VoidCallback? onDidPush,
  4. VoidCallback? onDidPop,
  5. VoidCallback? onDidPushNext,
  6. List<Object?> keys = const [],
})

Implementation

void useRouteAware({
  required RouteObserver observer,

  /// Called when the top route has been popped off, and the current route shows up.
  VoidCallback? onDidPopNext,

  /// Called when the current route has been pushed.
  VoidCallback? onDidPush,

  /// Called when the current route has been popped off.
  VoidCallback? onDidPop,

  /// Called when a new route has been pushed, and the current route is no longer visible.
  VoidCallback? onDidPushNext,
  List<Object?> keys = const [],
}) {
  final context = useContext();
  final route = ModalRoute.of(context);

  useEffect(
    () {
      if (route == null) throw Exception('No route found');

      final callbacks = _RouteCallbacks(
        onDidPop: onDidPop,
        onDidPopNext: onDidPopNext,
        onDidPush: onDidPush,
        onDidPushNext: onDidPushNext,
      );
      observer.subscribe(callbacks, route as PageRoute);

      return () => observer.unsubscribe(callbacks);
    },
    [route, observer, ...keys],
  );
}