【问题标题】:Persistent BottomNavigationBar with Routing in FlutterFlutter 中带路由的 Persistent BottomNavigationBar
【发布时间】:2020-09-29 11:39:59
【问题描述】:

我很难在 Flutter 中实现持久的BottomNavigationBar。我的目标是创建一个具有多个屏幕和多个路线的应用程序(最小示例):

我找到了this 中等文章,在实现了一些挣扎之后,我认为我找到了完美的解决方案。 但由于我想实现将用户发送回 LoginScreen 的注销功能,因此路由无法按预期工作...

正如您在 gif 中看到的,在单击注销按钮后会出现问题。 LoginScreen get 不是返回到 LoginScreen,而是通过 BottomNavigationBar 嵌入到 MainScreen 中。

如何改变这种行为?我以为我会删除带有pushAndRemoveUntil的所有路线...

// Navigate back to the LoginScreen (this doesn't work as expected...)
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(
                builder: (context) => LoginScreen(),
              ),
              (Route<dynamic> route) => false);

这是一个最小的可重现示例:https://github.com/klasenma/persistent_bottomnavigationbar

【问题讨论】:

    标签: flutter dart routes navigation


    【解决方案1】:

    经过几次尝试,我设法解决了这个问题。我需要保存 MainScreen 的上下文(index.dart -> 包含 BottomNavigationBar)。

    class ContextKeeper {
      static BuildContext buildContext;
    
      void init(BuildContext context) {
        buildContext = context;
      }
    }
    

    lib/screens/main/index.dart:

    @override
    void initState() {
      super.initState();
      ContextKeeper().init(context); // Save the context
    }
    

    然后改变

    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginScreen(),),(Route<dynamic> route) => false);
    

     Navigator.of(ContextKeeper.buildContext).pushNamedAndRemoveUntil(LoginScreen.id, (route) => false);
    

    它的工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2019-09-17
      • 2020-10-11
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多