Flutter Navigator popUntil 方法不会在我想要的命名路由处停止,并弹出所有屏幕

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

我有这段代码,我想弹出所有屏幕,直到它到达名称为“/”的基本屏幕。

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

在我调用 popUntil 方法之前,我使用了导航:

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

但我得到的结果是所有屏幕都弹出,直到进入黑屏。我应该改变什么让它停在“/”?

设置方法如下:

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


您的 MaterialApp 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 没有与 / 路由名称关联的路由。