如何不重复执行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 with AutomaticKeepAliveClientMixin{
  @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 with SingleTickerProviderStateMixin {
  int _bottomIndex = 0;
  Color activeColor = AppColor.PRIMARY_COLOR;
  List _titles = ["首页", "我的"];

  @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: [
            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

你可能感兴趣的:(如何不重复执行TabBarView中的widget的initState方法)