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()],
      ),
    ));
  }
相关推荐
GitLqr2 小时前
Flutter 居然能直接跑在 Apple Watch 上了?玩转 flutter-watchos
flutter·全栈·apple watch
vx-程序开发3 小时前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
宿6743 小时前
tsconfig.node.json
前端·javascript·vue.js
lilian2334 小时前
Harmony os 技术实战|拼豆制图10:把取消、解析失败和保存失败写成可恢复状态机
java·javascript·华为·harmonyos
海上小飞龙4 小时前
Redis 持久化:RDB 与 AOF
数据库·redis·缓存
只会cv的小前端4 小时前
七巧低代码表单JS脚本教学
开发语言·javascript·低代码
huabuyu4 小时前
SourceMap:从「看不懂线上报错」到「让 AI 定位真根因」
前端·javascript
এ慕ོ冬℘゜4 小时前
前端树形二级列表渲染 + 页面传参完整实战解析(附原生jQuery源码)
前端·javascript·jquery
用户24171401418605 小时前
一个 Tapas 菜单 App,逼我啃下了前端存储和 this 绑定两座大山
javascript
xiaominlaopodaren5 小时前
three.js地图数学基础(二):Web Mercator
javascript·gis·three.js