Flutter PageView中页面缓存

初学者第一次使用 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>

从源码中可以看到,它的作用就是保存页面状态,使用要求如下。

  1. 只能作用于 State 的子类,这个好理解,毕竟是保存页面状态;
  2. 实现 wantKeepAlive ,设置为 true 则表示要缓存页面状态;
  3. 在 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(        
    );
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容