在 TabBarView 组件中切换页面时,子页面每次均会重新 initState 一次,导致每次都切换页面均会重绘,如下图
如果需要只在第一次进页面 initState 一次,后面再进入页面不再 initState ,需要在子页面加上以下内容
首先在继承的类后面加上 with AutomaticKeepAliveClientMixin
with AutomaticKeepAliveClientMixin
然后在类中加入
@override
bool get wantKeepAlive => true; ///see AutomaticKeepAliveClientMixin
最后在build中加入
super.build(context); /// see AutomaticKeepAliveClientMixin
完整代码如下
import 'package:flutter/material.dart'; class Pages extends StatefulWidget{
@override
_PagesState createState() => _PagesState();
} class _PagesState extends State<Pages> with AutomaticKeepAliveClientMixin{ @override
bool get wantKeepAlive => true; ///see AutomaticKeepAliveClientMixin @override
Widget build(BuildContext context) {
super.build(context); /// see AutomaticKeepAliveClientMixin
// TODO: implement build
return Container();
}
}
完成效果如下,此时仅在第一次进入页面时会执行initState