flutter - 回页颤动时记住bottomNavigation bar的状态
问题描述
在main_activity.dart
中,有 4 个底部导航栏,分别命名为 A、B、C 和 D。
main_activity.dart
class MainPage extends StatefulWidget {
static const ROUTE = '/mainPage';
@override
State<StatefulWidget> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _selectedIndex = 2;
final _tabs = [
A(),
B(),
C(),
D(),
];
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
body: _tabs[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
items: [
...
],
onTap: (index) => setState(() {
_selectedIndex = index;
}),
),
),
onWillPop: () => _requestPop(context),
);
}
}
最初它将在选项卡 C 中打开页面。当我单击选项卡 B 时,它将显示包含浮动操作按钮的 B 页面。单击浮动操作按钮时,它将调用add_B.dart
. 我的问题是当我单击中的后退按钮时add_B.dart
,它将返回main_activity
并打开标签 C 页面。我怎样才能让它打开标签B页面呢?
add_B.dart
onWillPop: (){
_backToPreviousPage(context);
},
void _backToPreviousPage(BuildContext context) {
Navigator.of(context).pushReplacementNamed(MainPage.ROUTE);
}
解决方案
您可以创建global.dart
文件并在其中声明int _selectedIndex = 2;
和导入文件,只要您将其设置_selectedIndex
为某个值,则该值将在整个应用程序中随您一起保存。
推荐阅读
- python - 在 matplotlib 中绘制条形图时没有聚合错误的数字类型
- mingw - 如何在 dll 关闭之前运行 mingw 析构函数
- javascript - 悬停功能不适用于 svg 路径
- haskell - 当`package.yaml`发生变化时,如何让Stack重建Cabal文件?
- c# - 如何禁用 Visual Studio 2012 弹出窗口?
- html - 如何在图片标签上使用后备 - Safari Webp
- r - 从 R 中的向量和列表列表中获取数据框
- model - 如何在 NuSMV 中传递变量
- apache - 限制 Apache 中的凉亭组件访问
- java - SharedPreferences 始终返回 true(回收站视图)