Flutter: BottomNavigationBar rebuilds Page on change of tab

后端 未结 5 2008
小蘑菇
小蘑菇 2020-12-13 03:50

I have a problem with my BottomNavigationBar in Flutter. I want to keep my page alive if I change the tabs.

here my implementation

BottomNavigation

5条回答
  •  青春惊慌失措
    2020-12-13 04:25

    None of the previous answers worked out for me.

    The solution to keep the pages alive when switching the tabs is wrapping your Pages in an IndexedStack.

    class Tabbar extends StatefulWidget {
      Tabbar({this.screens});
    
      static const Tag = "Tabbar";
      final List screens;
      @override
      State createState() {
      return _TabbarState();
      }
    }
    
    class _TabbarState extends State {
      int _currentIndex = 0;
      Widget currentScreen;
    
      @override
      Widget build(BuildContext context) {
        var _l10n = PackedLocalizations.of(context);
    
        return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: widget.screens,
      ),
      bottomNavigationBar: BottomNavigationBar(
        fixedColor: Colors.black,
        type: BottomNavigationBarType.fixed,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(
            icon: new Icon(Icons.format_list_bulleted),
            title: new Text(_l10n.tripsTitle),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.settings),
            title: new Text(_l10n.settingsTitle),
          )
        ],
      ),
    );
      }
    
      void onTabTapped(int index) {
        setState(() {
          _currentIndex = index;
        });
      }
    }
    

提交回复
热议问题