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()],
      ),
    ));
  }
相关推荐
努力只为躺平2 分钟前
一文搞懂 Promise 并发控制:批量执行 vs 最大并发数,实用场景全解析!
前端·javascript
Web小助手4 分钟前
大保剑:Promise的有趣体验
javascript
李大玄4 分钟前
Google浏览器拓展工具 "GU"->google Utils
前端·javascript·github
爱编程的喵5 分钟前
从DOM0到事件委托:揭秘JavaScript事件机制的性能密码
前端·javascript·dom
sunbyte17 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ContentPlaceholder(背景占位)
前端·javascript·css·vue.js·tailwindcss
谦哥1 小时前
Claude4免费Vibe Coding!目前比较好的Cursor替代方案
前端·javascript·claude
心在飞扬1 小时前
理解JS事件环(Event Loop)
前端·javascript
敲代码的玉米C1 小时前
深入理解链表反转:从基础到进阶的完整指南
javascript
山有木兮木有枝_2 小时前
JavaScript 设计模式--单例模式
前端·javascript·代码规范
10年前端老司机2 小时前
React 受控组件和非受控组件区别和使用场景
前端·javascript·react.js