美文网首页
Flutter PageView中页面缓存

Flutter PageView中页面缓存

作者: 云飞扬1 | 来源:发表于2023-04-26 10:58 被阅读0次

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

    相关文章

      网友评论

          本文标题:Flutter PageView中页面缓存

          本文链接:https://www.haomeiwen.com/subject/prrvjdtx.html