flutter - Flutter 中带路由的 Persistent BottomNavigationBar
问题描述
我很难在 Flutter 中实现持久的BottomNavigationBar。我的目标是创建一个具有多个屏幕和多个路线的应用程序(最小示例):
我找到了这篇中型文章,在实现了一些努力之后,我认为我找到了完美的解决方案。但是因为我想实现一个注销功能,将用户发送回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.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);
它的工作原理。
推荐阅读
- jquery - 我有一个圆形进度条,我想根据百分比更改进度条的颜色,但似乎无法做到(使用 jsp)
- r - 如何计算 R 中对数正态分布的比例和形状参数?
- c# - 我如何知道服务是否需要一个字符串数组?
- python - 如果差值大于某个值,则在列表中保留连续数字
- python - 在 Python 中复制迭代器
- javascript - 如何在多折线图中打开和关闭数据点以及线条
- javascript - 在指针位置上使用 css scale() 放大/缩小作为原点会使 div 跳来跳去
- r - 如何将 .txt 冒号分隔的键值对列表转换为以段落分隔的大小写(Rstudio)
- c# - 如何使用 c# 更新 cosmos db 文档
- lua - 给定 lua 脚本中 for 循环语法的解释