在 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

