首页 > 解决方案 > 回页颤动时记住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);
  }

标签: flutterrouterbottomnavigationview

解决方案


您可以创建global.dart文件并在其中声明int _selectedIndex = 2; 和导入文件,只要您将其设置_selectedIndex为某个值,则该值将在整个应用程序中随您一起保存。


推荐阅读