How to preserve widget states in flutter, when navigating using BottomNavigationBar?

后端 未结 6 1425
青春惊慌失措
青春惊慌失措 2020-11-27 12:20

I\'m currently working on building a Flutter app that will preserve states when navigating from one screen, to another, and back again when utilizing BottomNavigationBar. Ju

6条回答
  •  时光取名叫无心
    2020-11-27 13:09

    Late to the party, but I've got a simple solution. Use the PageView widget with the AutomaticKeepAliveClinetMixin.

    The beauty of it that it doesn't load any tab until you click on it.


    The page that includes the BottomNavigationBar:

    var _selectedPageIndex;
    List _pages;
    PageController _pageController;
    
    @override
    void initState() {
      super.initState();
    
      _selectedPageIndex = 0;
      _pages = [
        //The individual tabs.
      ];
    
      _pageController = PageController(initialPage: _selectedPageIndex);
    }
    
    @override
    void dispose() {
      _pageController.dispose();
    
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      ...
        body: PageView(
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          children: _pages,
        ),
       bottomNavigationBar: BottomNavigationBar(
          ...
          currentIndex: _selectedPageIndex,
          onTap: (selectedPageIndex) {
            setState(() {
              _selectedPageIndex = selectedPageIndex;
              _pageController.jumpToPage(selectedPageIndex);
            });
          },
      ...
    }
    

    The individual tab:

    class _HomeState extends State with AutomaticKeepAliveClientMixin {
      @override
      bool get wantKeepAlive => true;
    
      @override
      Widget build(BuildContext context) {
        //Notice the super-call here.
        super.build(context);
        ...
      }
    }
    

    I've made a video about it here.

提交回复
热议问题