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()],
      ),
    ));
  }
相关推荐
Lionel6891 小时前
Flutter 鸿蒙:获取真实轮播图API数据
flutter
消失的旧时光-19431 小时前
第十四课 · 实战篇:Redis 缓存系统落地指南(Spring Boot 从 0 到可用)
spring boot·redis·缓存
凉辰1 小时前
使用uni.createInnerAudioContext()播放指定音频(踩坑分享功能)
开发语言·javascript·音视频
echoVic2 小时前
多模型支持的架构设计:如何集成 10+ AI 模型
java·javascript
echoVic2 小时前
AI Agent 安全权限设计:blade-code 的 5 种权限模式与三级控制
java·javascript
David凉宸2 小时前
Vue 3 + TS + Vite + Pinia vs Vue 2 + JS + Webpack + Vuex:对比分析
javascript·vue.js·webpack
boooooooom2 小时前
Pinia必学4大核心API:$patch/$reset/$subscribe/$onAction,用法封神!
javascript·vue.js·面试
千逐682 小时前
《基于 Flutter for OpenHarmony 的沉浸式天气可视化系统设计与实现》
flutter
一只大侠的侠2 小时前
Flutter开源鸿蒙跨平台训练营 Day8获取轮播图网络数据并实现展示
flutter·开源·harmonyos
不会敲代码12 小时前
解密JavaScript内存机制:从执行上下文到闭包的全景解析
javascript