如何不重复执行TabBarView中的widget的initSt
2018-12-25 本文已影响70人
o动感超人o
首先说一下,这两种方法只是做到只执行一次initState,并不能做到只执行一次build方法。
有2种方法
- 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>{
@protected
bool get wantKeepAlive=>true;
}
- 使用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,
);
}
}
以上两种方法都可以做到在切换的时候TabBarView中的widget的initState方法只执行一次,如果非要像Android原生代码一样缓存页面也有办法,我留个链接:
https://juejin.im/post/5b73c3b3f265da27d701473a
不过他这种方法我不知道是缓存widget还是只是不多次执行widget的initState方法,我也没有测试