Flutter swipe back gesture using nested navigators

Viewed 827

I have a main navigator that push others child navigators, but if I push a route from a child navigator, on iOS when I swipe back from the open widget, it comes back to main navigator root instead to go to the root of the child widget, so how can I handle the history of the child navigator first with the swipe gesture and allow to go back on main navigator only if I'm on the root of the child (like a single navigator) ?

This is the main navigator:

class MenuNavigator extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey;

  const MenuNavigator({Key key, this.navigatorKey}) : super(key: key);

  WidgetBuilder routeBuilder(
      RouteSettings routeSettings, GetUserResponse userResponse) {
    switch (routeSettings.name) {
      case MenuNavigatorRoutes.root:
        return (context) => MenuPage();
      case MenuNavigatorRoutes.documents:
        return (context) => DocumentsNavigator();
      case MenuNavigatorRoutes.requests:
        return (context) => RequestsNavigator();
      default:
        return null;
    }
  }

  @override
  Widget build(BuildContext context) {
     return Navigator(
          key: navigatorKey,
          initialRoute: MenuNavigatorRoutes.root,
          onGenerateRoute: (routeSettings) {
            return MaterialPageRoute(
                settings: routeSettings,
                builder: (context) =>
                    routeBuilder(routeSettings, userResponse)(context));
          },
        );
  }
}

DocumentsNavigator and RequestsNavigator are the child navigators and have the same structure of MenuNavigator but handle others routes.

2 Answers

I just discovered that if you wrap your nested navigator with:

WillPopScope(
        child: NestedNavigator(initialRoute: ...),
        onWillPop: () async =>
            !Navigator.of(context).userGestureInProgress));

It works!

This worked for me. WillPopScope is only added when more then 1 page in nested navigator.

@override
Widget build(BuildContext context) {
  return NestedNavigator(
    navigator: Navigator(
      key: navigatorKey,
      onPopPage: _handlePopPage,
      pages: [],
    ),
  );
}

import 'package:flutter/widgets.dart';

class NestedNavigator extends StatelessWidget {
  const NestedNavigator({
    super.key,
    required this.navigator,
  });

  final Navigator navigator;

  @override
  Widget build(BuildContext context) {
    if (navigator.pages.length > 1) {
      return WillPopScope(
        onWillPop: () async => !Navigator.of(context).userGestureInProgress,
        child: navigator,
      );
    }
    return navigator;
  }
}
Related