Flutter
切换tabar
后不会保留tabbar
状态 ,Flutte
r中为了节约内存不会保存widget
的状态,widget
都是临时变量。当我们使用TabBar
,TabBarView
是我们就会发现,切换tabar
,initState
又会被调用一次。
怎么为了让tabar
一直保存在内存中,不被销毁?
添加AutomaticKeepAliveClientMixin
,并设置为bool get wantKeepAlive => true;
,这样就能一直保持当前不被initState
了。
class TestListView extends StatefulWidget {
@override
_ChatPageState createState() => _ChatPageState();
}
//1.添加with AutomaticKeepAliveClientMixin
class _TestListViewState extends State<TestListView>
with AutomaticKeepAliveClientMixin {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
//3.添加 super.build(context) 必须添加
super.build(context);
return Container();
}
//2.添加 bool get wantKeepAlive => true
//不会被销毁,占内存中
@override
bool get wantKeepAlive => true;
}
1.添加with AutomaticKeepAliveClientMixin
class _TestListViewState extends State<TestListView>
with AutomaticKeepAliveClientMixin{}
2.添加 bool get wantKeepAlive => true
,是否保保持页面不变
@override
bool get wantKeepAlive => true;
3.添加 super.build(context)
必须添加
@override
Widget build(BuildContext context) {
//3.添加 super.build(context) 必须添加
super.build(context);
return Container();
}