如何不重复执行TabBarView中的widget的initState方法

首先说一下,这两种方法只是做到只执行一次initState,并不能做到只执行一次build方法。
有2种方法

  1. TabBarView中的widget需要继承StatefulWidget,然后它的State继承AutomaticKeepAliveClientMixin,wantKeepAlive返回true,例如下面的代码:
class HomePage extends StatefulWidget {

  @override
  HomePageState createState() {
    return new HomePageState();
  }
}
class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin<HomePage>{
  @override
  Widget build(BuildContext context) {
    super.build(context);
  }
  @protected
  bool get wantKeepAlive=>true;
}
  1. 使用TabBarView的widget使用IndexedStack存储页面,这样的话_HomePageState可以不需要继承AutomaticKeepAliveClientMixin
class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin<MainPage> {
  int _bottomIndex = 0;
  Color activeColor = AppColor.PRIMARY_COLOR;
  List<String> _titles = <String>["首页", "我的"];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: App.APP_NAME,
      theme: ThemeData(
        primarySwatch: AppColor.PRIMARY_COLOR,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Center(
            child: Text(_titles[_bottomIndex]),
          ),
        ),
        body: body: IndexedStack(
          children: <Widget>[
            HomePage(),
            MePage(),
          ],
          index: _bottomIndex,
        ),
        bottomNavigationBar: BottomNavigationBar(
            currentIndex: _bottomIndex,
            onTap: (index) {
              setState(() {
                _bottomIndex = index;
              });
            },
            items: [
              BottomNavigationBarItem(
                  activeIcon: Icon(Icons.home, color: _bottomIndex == 0 ? activeColor : null),
                  icon: Icon(Icons.home),
                  title: Text(_titles[0])),
              BottomNavigationBarItem(
                  activeIcon: Icon(Icons.person, color: _bottomIndex == 1 ? activeColor : null),
                  icon: Icon(Icons.person),
                  title: Text(_titles[1]))
            ]),
      ),
      initialRoute: AppRoute.ROUTE_MAIN,
    );
  }
}

但是用过TabView以后就会发现有很多bug,在我的这篇文章里解决了该问题
https://juejin.im/post/5cde82346fb9a07f04201760

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 原文在此,此处只为学习 Widget与ElementWidget主要接口Stateless WidgetState...
    lltree阅读 9,984评论 0 1
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,473评论 1 45
  • 前几天听到这样一个问题:“如果生命只剩下最后一天,你有多少遗憾”?一开始没有注意到这个问题的深度,后来经过将近一个...
    尘尘ccq阅读 10,425评论 0 1
  • 不管我愿不愿意,我还是30岁了。 我郁闷,我惆怅,我抗拒,可是我还是必须接受。我心里一直暗示自己,我不想不想长大,...
    卓悦人生阅读 1,418评论 0 0
  • 停更了好久,每次都是拖延拖延再拖延,每次都是希望主题阅读/观影完毕后再输出,但是我这种想法天天在变的人很难坚持一段...
    钱多萝阅读 2,532评论 0 0

友情链接更多精彩内容