Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routes returning null while calling popUntil on GlobalKey<NavigatorState>

I am using global key to handle my navigations. The main.dart, routes and NavigationService are as below. The main purpose of using the global keys is to make the navigation independent of context so that the network modules can auto log user out via the dio interceptor if the refresh token expires.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
          return MaterialApp(
          title: 'AZY APP',
          navigatorKey: locator<NavigationService>().navigatorKey,
          onGenerateRoute: router.generateRoute,
          home: HomePageScreen())
          
}}

NavigationService.dart

class NavigationService {
  final GlobalKey<NavigatorState> navigatorKey =
      new GlobalKey<NavigatorState>();

  Future<dynamic> navigateTo(String routeName, {dynamic arguments}) {
    return navigatorKey.currentState.pushNamed(routeName, arguments: arguments);
  }

  pop(value) {
    print("pop");
    return navigatorKey.currentState.pop(value);
  }

  goBack() {
    print("goback");
    return navigatorKey.currentState.pop();
  }

  popUntil(String desiredRoute) {
    return navigatorKey.currentState.popUntil((route) {
      print("${route.settings.name}");
      return route.settings.name == desiredRoute;
    });
  }

  pushReplacementNamed(String route) {
    print("pushReplacementNamed");
    return navigatorKey.currentState.pushReplacementNamed(route);
  }
}

Routes.dart


Route<dynamic> generateRoute(RouteSettings settings) {
  final args = settings.arguments;

  switch (settings.name) {
    case routes.SplashScreenRoute:
      return MaterialPageRoute(builder: (context) => SplashScreen());

    case routes.LoginScreenRoute:
      return MaterialPageRoute(builder: (context) => LoginScreen());

    case routes.MainPageScreenRoute:
      return MaterialPageRoute(builder: (context) => MainPageScreen());

    case routes.HomePageScreenRoute:
      return MaterialPageRoute(builder: (context) => HomePageScreen());

    default:
      return MaterialPageRoute(
        builder: (context) => Scaffold(
          body: Center(
            child: Text('Error Loading Screen'),
          ),
        ),
      );
  }
}

All the functions in NavigationService works well except popUntil. For every route, settings.name is null so i am unable to using navigatorkey with popUntil.

Log of print("${route.settings.name}")

Log of print("${route.settings.name}").

like image 654
mr_sh Avatar asked Mar 02 '23 02:03

mr_sh


1 Answers

The problem was that I was not passing route settings to MaterialPageRoute in my router.

MaterialPageRoute(
          settings: settings, builder: (context) => SplashScreen());
like image 132
mr_sh Avatar answered May 30 '23 05:05

mr_sh