如何在不调用ModalRoute.withName的初始化状态并忘记路径的情况下使用popuntil?

时间:2020-07-17 08:36:14

标签: flutter dart navigator

当前屏幕距离主屏幕3页 我想回到主画面 无需在主屏幕上调用initState, 返回主屏幕后,按导航键一定不能转到第3页。

我只想要popAndReplacementNamed,但我只有popAndPushNamed

1 个答案:

答案 0 :(得分:1)

您需要的是 Navigator.popUntil()方法。

在这种方法中,您可以通过提及要到达的屏幕来指定要返回的屏幕数。

例如,假设您已导航:

主屏幕->屏幕1->屏幕2->屏幕3

现在您在screen3上,并且想要转到主屏幕。所以你必须使用

Navigator.popUntil(context , ModalRoute.withName("/home-screen") );

(考虑“ / home-screen”是您的路线名称)

如果尚未配置main.dart,应如何配置路由,

 @override
  Widget build(BuildContext context) {
   return MaterialApp(
          title: 'Flutter app',
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.darkTheme,
          initialRoute: "/home-screen",
          routes: {
            "/home-screen": (ctx) => Home(),
            "/screen1": (context) => FirstScreen(),
            "/screen2": (context) => SecondScreen(),
            "/screen3": (context) => ThirdScreen(),
          },
        );
    
  }

更重要的是为您的路线命名。