底部导航栏不会在颤动中切换标签

bottom navigation bar not switching tabs in flutter

我想在 flutter 中使用花哨的底部导航。当我在选项卡之间切换时,它仅在导航栏上显示选项卡切换,但是主体没有切换。当我切换时,它没有显示其他选项卡。 这是我的代码

return Scaffold(
  body: _getPage(currentPage),
   bottomNavigationBar: FancyBottomNavigation(
          key: bottomNavigationKey,
          tabs: [
            TabData(iconData: Icons.home,title: 'Home'),
            TabData(iconData: Icons.search, title: 'Search'),
            TabData(iconData: Icons.person, title: 'Profile'),
          ],
          onTabChangedListener:   (position){
            setState(() {
              currentPage = position;
              final FancyBottomNavigationState fState =
                  bottomNavigationKey.currentState;
              fState.setPage(position);
              print('currentPage = $currentPage');
            });
          },
        )
);

_getPage(int page){
  switch(page) {
    case 0:
      return Page1();
    case 1:
      return Search();
    case 2:
      return Profile();
  }
}

这里不需要GlobalKey。只需在 setState 中设置 currentPage 值即可。

Dev Nathan Withers 在第 48 到 50 行写 here that the key prop defaults to null and is only used for Programmatic Selection of tabs. This special use case is only relevant if you want to change tabs by not clicking on the actual buttons. You don't need this feature. You can check out the example 实际 use-case 关键道具。

同时检查 IndexedStack 是否适合您。它保存页面状态。你是 _getPage() 方法在每个开关上销毁和构建每个新页面。

我在这个例子中把所有东西放在一起:

class _HomePageState extends State<HomePage> {
  int _currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: IndexedStack(
          index: _currentPage,
          children: [StartView(), AllServicesView()],
        ),
      ),
      bottomNavigationBar: FancyBottomNavigation(
        tabs: [
          TabData(iconData: Icons.home,title: 'Home'),
          TabData(iconData: Icons.search, title: 'Search'),
        ],
        onTabChangedListener: (position){
          setState(() {
            _currentPage = position;
            print('currentPage = $_currentPage');
          });
        },
      )
    );
  }