首页 > 解决方案 > Flutter 中带路由的 Persistent BottomNavigationBar

问题描述

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

最小示例的应用程序结构

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

gif

正如您在 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

标签: flutterdartroutesnavigation

解决方案


经过几次尝试,我设法解决了这个问题。我需要保存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);

它的工作原理。


推荐阅读