Flutter bottomNavigationBar切换widget页面后重复创建widget的问题

问题描述:使用 bottomNavigationBar +pageView切换页面,切换第二个页面后再次切换第一个页面,发现重复创建触发了网路请求,好坑!

Widget build(BuildContext context) {
    return Scaffold(
      body: PageView.builder(
        controller: _pageController,
        itemCount: _bodyList.length,
        itemBuilder: (BuildContext context, int index) {
          return _bodyList[index];
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        onTap: (index) {
          //点击触发 切换 currentIndex;
          setState(() {
            _currentNavigationBarItem = index;
          });
          _pageController.animateToPage(index,
              duration: Duration(microseconds: 1), curve: Curves.ease);
        },
        currentIndex: _currentNavigationBarItem,
        items: _bottomNavigationBarItemList,
      ),
    );
  }

解决方法1: pageveiw的children 实现 AutomaticKeepAliveClientMixin (官方推荐做法); 参考掘金

解决方法2:使用 CupertinoTabScaffold;

因为 苹果风格的TabScaffold(脚手架)构建时 指定了tab页面,没有切换页面后重复创建的问题;

@override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
          items: [
            buildBottomNavigationBarItem(
                "首页",
                "assets/images/ic_tab_fortune_normal.png",
                "assets/images/ic_tab_fortune_selected.png"),
            buildBottomNavigationBarItem(
                "视频",
                "assets/images/ic_tab_video_normal.png",
                "assets/images/ic_tab_video_selected.png"),
            buildBottomNavigationBarItem(
                "热销",
                "assets/images/ic_tab_hot_normal.png",
                "assets/images/ic_tab_hot_selected.png"),
            buildBottomNavigationBarItem(
                "自选",
                "assets/images/ic_tab_chosen_normal.png",
                "assets/images/ic_tab_chosen_selected.png"),
            buildBottomNavigationBarItem(
                "我的",
                "assets/images/ic_tab_mine_normal.png",
                "assets/images/ic_tab_mine_selected.png"),
          ],
        ),
        tabBuilder: (BuildContext context, int index) {
          switch (index) {
            case 0:
              return MainPage();
              break;
            case 1:
              return VideoPage();
              break;
            case 2:
              return HotSalePage();
              break;
            case 3:
              return SelectPage();
              break;
            case 4:
              return MinePage();
              break;
          }
        });
  }

 

你可能感兴趣的:(android,flutter)