初學者第一次使用 PageView 時层坠,肯定會發(fā)現(xiàn)頁面切換出去再切回來時适肠,該頁面會重建公罕。要做到像原生中那樣的頁面緩存梳杏,需要用到 AutomaticKeepAliveClientMixin
棺聊。
/// A mixin with convenience methods for clients of [AutomaticKeepAlive]. Used
/// with [State] subclasses.
///
/// Subclasses must implement [wantKeepAlive], and their [build] methods must
/// call `super.build` (though the return value should be ignored).
///
/// Then, whenever [wantKeepAlive]'s value changes (or might change), the
/// subclass should call [updateKeepAlive].
///
/// The type argument `T` is the type of the [StatefulWidget] subclass of the
/// [State] into which this class is being mixed.
///
/// See also:
///
/// * [AutomaticKeepAlive], which listens to messages from this mixin.
/// * [KeepAliveNotification], the notifications sent by this mixin.
@optionalTypeArgs
mixin AutomaticKeepAliveClientMixin<T extends StatefulWidget> on State<T>
從源碼中可以看到伞租,它的作用就是保存頁面狀態(tài),使用要求如下限佩。
- 只能作用于 State 的子類葵诈,這個好理解,畢竟是保存頁面狀態(tài)祟同;
- 實現(xiàn)
wantKeepAlive
作喘,設置為 true 則表示要緩存頁面狀態(tài); - 在 State 類的
build
方法中必須調(diào)用super.build
方法晕城;
一個簡單的完整例子如下:
///1. 混入 AutomaticKeepAliveClientMixin 這個 mixin
class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
///2. 設置為 true 則表示保存頁面狀態(tài)
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
///3. 必須調(diào)用 super 方法
super.build(context);
return Container(
);
}
}