Flutter中BottomNavigationBar+PageView+AutomaticKeepAliveClientMixin实现底部tabbar切换页面状态保持

  • 网上有很多方案,试了一下,简单的BottomNavigationBar+AutomaticKeepAliveClientMixin是不能实现页面状态保持的.同时BottomNavigationBar+IndexedStack+AutomaticKeepAliveClientMixin会出现进入首页就把tababr的几个页面都加载的情况,也不是最优方案.最终解决问题的方案就是:BottomNavigationBar+PageView+AutomaticKeepAliveClientMixin.直接上代码
class _TabbarPageState extends State {
  PageController _pageController;
  int currentIndex = 0;
  List pagesLists = [

    HomePageView(),
    LeavePageView(),
    MinePageView(),

  ];
  List navTitleLsit = ["首页", "请假","我的"];
  @override
  void initState() {
    _pageController = PageController(initialPage: 0);
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.kColor_ListViewbackGround,
    body: PageView.builder(
      controller: _pageController,
      itemCount: pagesLists.length,
      physics: NeverScrollableScrollPhysics(),
      itemBuilder: (context, index) {
        return pagesLists[index];
      },
      onPageChanged: (index) {
        setState(() {
          currentIndex = index;
        });
      },
    ),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        //选中和未选中设置一样的字体大小,就不会出现类似动画的情况
        selectedFontSize: 14,
        unselectedFontSize: 14,
        //不设置显示不出文字
        type: BottomNavigationBarType.fixed,
        //设置选中时的颜色
        selectedItemColor: AppColors.kColor_NavgationBar,
        currentIndex: currentIndex,
        items: [
          buliderBottomNavgationBarItem("home", navTitleLsit[0]),
          buliderBottomNavgationBarItem("leave", navTitleLsit[1]),
          buliderBottomNavgationBarItem("me", navTitleLsit[2])
        ],
        onTap: (index) {
          _pageController.jumpToPage(index);
        },
      ),
    );
  }
  BottomNavigationBarItem buliderBottomNavgationBarItem(
      String imageNameStr, String titleStr) {
    return BottomNavigationBarItem(
        icon: Image.asset("images/tabimages/${imageNameStr}_close.png",
            //下面两行代码解决点击icon时会发生闪动的情况
            excludeFromSemantics: true,
            gaplessPlayback: true,
            width: 23),
        activeIcon: Image.asset(
          "images/tabimages/${imageNameStr}_open.png",
          excludeFromSemantics: true,
          gaplessPlayback: true,
          width: 23,
        ),
        label: titleStr);
  }
}
  • 页面中的的代码
1.class _MinePageViewState extends State with AutomaticKeepAliveClientMixin
2.@override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
3.super.build(context);
  • 以上就实现了想要的功能

你可能感兴趣的:(Flutter中BottomNavigationBar+PageView+AutomaticKeepAliveClientMixin实现底部tabbar切换页面状态保持)