ImaGiraffe
ImaGiraffe

Reputation: 33

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

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());
    }
  }
}


Upvotes: 2

Views: 1811

Answers (2)

Vinicius Victor
Vinicius Victor

Reputation: 358

As you're likely aware, if you use onGenerateRoute you can't use routes property of MaterialApp to define routes with same name, because one replaces the other. Still, if you want to use PageRouteBuilder to animate transitions from one screen to another, the simplest way is to use onGenerateRoute.

When testing with this, I found out that onGenerateRoute will not name the routes on your PageRouteBuilder, meaning popUntil will pop every screen from your navigator stack.

The simplest way of fixing this is passing the RouteSettings parameter from onGenerateRoute into your PageRouteBuilder, as such:

return PageRouteBuilder(
  settings: routeSettings,
  pageBuilder: (context, animation, secondaryAnimation) => page,
  ...
);

Upvotes: 1

Nico Spencer
Nico Spencer

Reputation: 1180

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.

Upvotes: 2

Related Questions