flutter中使用缓存

前言

在flutter项目中使用ListView或者PageView等有滚动条组件的时候,切换页面的时候,再切换回来会丢失之前的滑动状态,这个时候就需要需要使用缓存功能

缓存类

dart 复制代码
import 'package:flutter/material.dart';

class KeepAliveWrapper extends StatefulWidget {
 const KeepAliveWrapper(
     {Key? key, @required this.child, this.keepAlive = true})
     : super(key: key);

 final Widget? child;
 final bool keepAlive;

 @override
 State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
   with AutomaticKeepAliveClientMixin {
 @override
 Widget build(BuildContext context) {
   return widget.child!;
 }

 @override
 bool get wantKeepAlive => widget.keepAlive;  
}

使用

在需要缓存的组件使用KeepAliveWrapper包裹一下即可

复制代码
@override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
        child: Scaffold(
      body: Stack(
        children: [_homePage(), _appBar()],
      ),
    ));
  }
相关推荐
ssshooter4 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live000006 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉6 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
忆江南6 小时前
iOS 深度解析
flutter·ios
球球pick小樱花6 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
喝水的长颈鹿6 小时前
【大白话前端 02】网页从解析到绘制的全流程
前端·javascript
明君879976 小时前
Flutter 实现 AI 聊天页面 —— 记一次 Markdown 数学公式显示的踩坑之旅
前端·flutter
用户14536981458786 小时前
VersionCheck.js - 让前端版本更新变得简单优雅
前端·javascript
codingWhat6 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
码路飞7 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python