在 Flutter 中使用路由的持久化 BottomNavigationBar

Persistent BottomNavigationBar with Routing in Flutter

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

我找到了 this 中篇文章,在努力实现之后,我认为我找到了完美的解决方案。 但是因为我想实现一个将用户发送回 LoginScreen 的注销功能,路由没有按预期工作...

正如您在 gif 中看到的,问题出现在单击注销按钮后。 LoginScreen 不是导航回 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

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

class ContextKeeper {
  static BuildContext buildContext;

  void init(BuildContext context) {
    buildContext = context;
  }
}

lib/screens/main/index.飞镖:

@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);

它起作用了。