Home > other >  Flutter Navigator popUntil method doesn't stop at the Named Route I want it to, and pops all th
Flutter Navigator popUntil method doesn't stop at the Named Route I want it to, and pops all th

Time:10-19

I have this bit of code that I want to pop all screens until it gets to the base screen with Name "/".

Navigator.of(context).popUntil(ModalRoute.withName("/"));

Before I call the popUntil method, I navigated using:

Navigator.of(context).pushNamed("/Loading");
Navigator.of(context).pushReplacementNamed("/Menu");

But the result I'm getting is all the screens are getting popped until it gets to the black screen. What should I change to make it stop at "/"?

Here is how it's set up:

main.dart

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'My App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        debugShowCheckedModeBanner: false,
        onGenerateRoute: AppRouter().onGenerateRoute,
        initialRoute: '/',
      ),
    );
  }
}

class AppRouter {
  Route? onGenerateRoute(RouteSettings routeSettings) {
    switch (routeSettings.name) {
      case '/':
        return MaterialPageRoute(builder: (_) => const LoadingScreen());
      case '/Menu':
        return MaterialPageRoute(builder: (_) => const MenuScreen());
      case '/Loading':
        return MaterialPageRoute(builder: (_) => const LoadingScreen());
    }
  }
}


CodePudding user response:

The ModalRoute.withName predicate is used when a route is tied to a specific route name. Because you're using onGenerateRoute (which is typically a last resort) instead of the routes table in your MaterialApp there is no route associated with the / route name.

  • Related