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()],
      ),
    ));
  }
相关推荐
驾驭人生37 分钟前
Hangfire.Redis.StackExchange 已归档停更!生产任务卡死、重复执行、网络抖动问题解决方案
数据库·redis·缓存
leoZ2311 小时前
第 6 篇:SchemaForm 渲染器核心实现
前端·javascript·vue.js·人工智能·神经网络·机器学习·自然语言处理
CoderYanger2 小时前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
还是大剑师兰特2 小时前
vue项目浏览器版本判别,低于IE11跳转到新页面
前端·javascript·vue.js
TDengine (老段)2 小时前
TDengine Catalog 与元数据缓存
大数据·数据库·物联网·缓存·时序数据库·tdengine
想吃火锅10052 小时前
【leetcode】42.接雨水js
开发语言·javascript·ecmascript
坚果的博客3 小时前
Flutter 三方库 phone_state 的 OpenHarmony 适配实战
flutter
雪芽蓝域zzs3 小时前
第十六节:递归组件实现无限层级折叠侧边栏菜单
开发语言·javascript·ecmascript
BillKu5 小时前
vue3 字符串排序 localeCompare,确保排序为 “B01“, “B10“, “B2“
前端·javascript·vue.js
然我5 小时前
从 Service 到生命周期:Agent Runtime 的插件内核
前端·javascript·agent