flutter中TabBar和TabBarView保持状态方法
程序员文章站
2022-06-01 18:38:17
...
flutter使用TabBarView组件分页显示数据,来回切换页面,会触发页面的init和build,而且页面会回到最顶端,需要加个保持状态,方法共3步:
1.在每个页面都混入with AutomaticKeepAliveClientMixin
class MyViewPageState extends State<MyViewPage>
with AutomaticKeepAliveClientMixin{
}
2.在这些页面里重写wantKeepAlive方法,写法固定的
class MyViewPageState extends State<MyViewPage>
with AutomaticKeepAliveClientMixin{
@override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
3.在这些页面的build开头调用super.build()
class MyViewPageState extends State<MyViewPage>
with AutomaticKeepAliveClientMixin{
@override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Container();
}
再来切换tab,会发现这这页面init和build不会重复调用,并且原来滚动到底端的页面,切回来还是在底端。