初学者第一次使用 PageView 时,肯定会发现页面切换出去再切回来时,该页面会重建。要做到像原生中那样的页面缓存,需要用到 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>
从源码中可以看到,它的作用就是保存页面状态,使用要求如下。
- 只能作用于 State 的子类,这个好理解,毕竟是保存页面状态;
- 实现
wantKeepAlive
,设置为 true 则表示要缓存页面状态; - 在 State 类的
build
方法中必须调用super.build
方法;
一个简单的完整例子如下:
///1. 混入 AutomaticKeepAliveClientMixin 这个 mixin
class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
///2. 设置为 true 则表示保存页面状态
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
///3. 必须调用 super 方法
super.build(context);
return Container(
);
}
}
网友评论