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()],
      ),
    ));
  }
相关推荐
一 乐1 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
xkxnq3 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
Van_Moonlight4 小时前
RN for OpenHarmony 实战 TodoList 项目:空状态占位图
javascript·开源·harmonyos
xkxnq4 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
BBBBBAAAAAi5 小时前
Claude Code安装记录
开发语言·前端·javascript
小北方城市网5 小时前
分布式锁实战指南:从选型到落地,避开 90% 的坑
java·数据库·redis·分布式·python·缓存
源码获取_wx:Fegn08956 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
Jing_Rainbow6 小时前
【 前端三剑客-37 /Lesson61(2025-12-09)】JavaScript 内存机制与执行原理详解🧠
前端·javascript·程序员
UIUV7 小时前
模块化CSS学习笔记:从作用域问题到实战解决方案
前端·javascript·react.js
Kakarotto7 小时前
使用ThreeJS绘制东方明珠塔模型
前端·javascript·vue.js