可重复使用的底部导航栏状态-不保留状态

时间:2019-10-08 23:52:19

标签: flutter

我创建了一个底部导航栏,每次在不同的页面中使用它时,其状态都回到第一项。我想念什么?谢谢。

列表(和main.dart文件)中定义了5条路由,因此除了状态之外,其他所有东西都运行良好。

我已经尝试过使用AutomaticKeepAliveClientMixin,但是我不确定我是否正确使用了它(在下面的代码中)。

代码如下:

class MyBottomNavigationBar extends StatefulWidget {
  MyBottomNavigationBar({Key key}) : super(key: key);

  @override
  MyBottomNavigationBarState createState() => MyBottomNavigationBarState();
}

class MyBottomNavigationBarState extends State<MyBottomNavigationBar>
    with AutomaticKeepAliveClientMixin {

  int bottomTabIndex = 0;
  var routes = ['/', '/', '/my_categories', '/my_people_list', '/my_chat'];

  @override
  bool get wantKeepAlive => true;

  @override
  void onTabTapped(int index) {
    setState(() {
      bottomTabIndex = index;
      Navigator.pushNamed(context, routes.elementAt(bottomTabIndex));
    });
  }

  @override
  Widget build(BuildContext context) {
    theme:
    MyFirstTheme().theme;

    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      //
      selectedLabelStyle: TextStyle(fontWeight: FontWeight.w700),
      unselectedLabelStyle: TextStyle(fontWeight: FontWeight.w700),
      iconSize: 24,
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text(
            'HOME',
          ),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.insert_chart),
          title: Text(
            'STATS',
          ),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.view_list),
          title: Text(
            'INVENTORY',
          ),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.group),
          title: Text(
            'PEOPLE',
          ),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.forum),
          title: Text(
            'CHAT',
          ),
        ),
      ],
      currentIndex: bottomTabIndex,
      onTap: onTabTapped,
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您需要PageStorage和PageStorageBucket
如果为bottomNavigationBar定义小部件,则需要传递页面索引
代码段

final List<Widget> pages = [
    FirstPage(
      key: PageStorageKey('Page1'),
    ),
    SecondPage(
      key: PageStorageKey('Page2'),
    ),
  ];
 ...
final PageStorageBucket bucket = PageStorageBucket();
...
@override
Widget build(BuildContext context) {
return Scaffold(
  bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
  body: PageStorage(
    child: pages[_selectedIndex],
    bucket: bucket,
  ),
);
}

您可以参考详细信息https://medium.com/@lucassaltoncardinali/keeping-state-with-the-bottom-navigation-bar-in-flutter-69e4168878e1
Github代码https://github.com/lscardinali/FlutterBottomNavigationBarStatePersistanceSample

演示github代码,您可以看到页面保持其状态

enter image description here