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()],
      ),
    ));
  }
相关推荐
奶昔不会射手17 小时前
自定义vue3函数式弹窗
前端·javascript·css
wuhen_n17 小时前
破冰——建立我们的AI开发实验环境
前端·javascript
张元清18 小时前
React Hooks vs Vue Composables:2026 年全面对比
前端·javascript·面试
yuki_uix18 小时前
从三个自定义 Hook 看 React 状态管理的设计思想
前端·javascript
CyrusCJA18 小时前
JavaScript原型与super关键字
前端·javascript·js
清水白石00819 小时前
Python 弱引用深度解析——让缓存不再成为内存泄漏的温床
java·python·缓存
難釋懷19 小时前
Redis搭建哨兵集群
数据库·redis·缓存
codeshareman19 小时前
JSON.stringify 在 React Hooks 依赖项里的坑:一次复盘
javascript
进击的尘埃19 小时前
把 LLM 吐出来的组件扔进 `iframe` 跑:沙箱隔离这件事没你想的那么简单
javascript
ujainu19 小时前
Electron 极简时钟应用开发全解析:托盘驻留、精准北京时间与 HarmonyOS PC 适配实战
javascript·electron·harmonyos