Flutter云端缓存管理插件cloud_cache的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter云端缓存管理插件cloud_cache的使用

简介

cloud_cache 是一个用于 Flutter 的云端缓存管理插件,类似于 Android 中的 RxCache。它基于 Dio(Flutter 的 HTTP 客户端)实现,并结合了 sqflite 作为磁盘缓存,LRU 策略作为内存缓存。

该插件受 flutter_cache_manager 启发。

Pub


添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  cloud_cache: ^0.2.x # 最新版本

运行 flutter pub get 来安装依赖。


快速开始

1. 在 Dio 中添加 dio-http-cache 拦截器

import 'package:dio/dio.dart';
import 'package:cloud_cache/cloud_cache.dart';

void main() {
  // 初始化 Dio 并添加缓存拦截器
  final dio = Dio();
  dio.interceptors.add(
    DioCacheManager(
      CacheConfig(baseUrl: "http://www.example.com"), // 设置基础 URL
    ).interceptor,
  );
}

2. 设置请求的最大缓存时间

Dio().get(
  "http://www.example.com",
  options: buildCacheOptions(Duration(days: 7)), // 设置缓存时间为 7 天
);

高级用法

1. 自定义配置参数

通过 buildCacheOptions 方法可以自定义缓存配置。

参数说明:

  • primaryKey: 默认使用 host + path 作为主键,也可以自定义。
  • subKey: 默认使用查询参数(queryParameters)作为子键,必要时可以指定子键。
  • maxAge: 设置缓存的有效期,如果未设置,则尝试从响应头获取。
  • maxStale: 设置缓存的过期时间,在发生错误(如 500、404)之前尝试返回缓存。
  • forceRefresh: 默认为 false,表示优先从网络获取数据。

示例代码:

Dio().get(
  "http://www.example.com",
  options: buildCacheOptions(
    Duration(days: 7), // 缓存有效期
    subKey: "page=1", // 子键
    maxStale: Duration(days: 10), // 允许的过期时间
    forceRefresh: true, // 强制刷新
  ),
);

2. 使用 CacheConfig 配置默认参数

通过 CacheConfig 可以设置全局默认参数。

参数说明:

  • baseUrl: 可选,如果未设置,则删除缓存时需要提供完整路径。
  • encrypt/decrypt: 必须配合使用以加密磁盘缓存数据。
  • defaultMaxAge: 默认缓存有效期,例如 Duration(days: 7)
  • defaultMaxStale: 类似于 defaultMaxAge
  • databasePath: 数据库路径。
  • databaseName: 数据库名称。
  • skipMemoryCache: 是否跳过内存缓存,默认为 false
  • skipDiskCache: 是否跳过磁盘缓存,默认为 false
  • maxMemoryCacheCount: 内存缓存的最大条目数,默认为 100。
  • defaultRequestMethod: 默认的 HTTP 请求方法,默认为 "POST"
  • diskStore: 自定义磁盘存储。

示例代码:

final dio = Dio();
dio.interceptors.add(
  DioCacheManager(
    CacheConfig(
      baseUrl: "http://www.example.com",
      defaultMaxAge: Duration(days: 7),
      defaultMaxStale: Duration(days: 10),
    ),
  ).interceptor,
);

3. 清理过期缓存

自动清理

缓存会自动清理过期数据,无需手动操作。

手动清理

如果需要手动清理过期缓存,可以调用以下方法:

DioCacheManager.clearExpired();

4. 删除缓存

4.1 按主键删除缓存

无论子键为何值,只要主键匹配即可删除缓存。

_dioCacheManager.deleteByPrimaryKey(path, requestMethod: "POST");

4.2 按主键和子键删除缓存

当主键和子键都匹配时,删除缓存。

_dioCacheManager.deleteByPrimaryKeyAndSubKey(
  path,
  requestMethod: "GET",
  queryParameters: {'k': keyword},
);

4.3 按主键和可选子键删除缓存

如果知道主键和子键的具体值,可以直接删除。

_dioCacheManager.delete(
  primaryKey,
  subKey: 'subKey',
  requestMethod: 'POST',
);

5. 清理所有缓存

清理所有缓存,包括过期和未过期的缓存。

_dioCacheManager.clearAll();

6. 判断数据是否来自缓存

可以通过检查响应头中的特定字段来判断数据是否来自缓存。

if (response.headers.value(DIO_CACHE_HEADER_KEY_DATA_SOURCE) != null) {
  // 数据来自缓存
} else {
  // 数据来自网络
}

示例:maxAgemaxStale 的用法

_dio.post(
  "https://www.example.com",
  data: {'k': "keyword"},
  options: buildCacheOptions(
    Duration(days: 3), // 缓存有效期
    maxStale: Duration(days: 7), // 允许的过期时间
  ),
);

解释:

  1. 0 ~ 3 天: 直接从缓存返回数据,与网络无关。
  2. 3 ~ 7 天:
    • 首先从网络获取数据。
    • 如果成功,更新缓存。
    • 如果失败或无网络,尝试从缓存中获取数据。
  3. 7 天以上: 不再使用缓存,缓存会在适当时候被删除。

许可证

Copyright 2019 Hurshi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

更多关于Flutter云端缓存管理插件cloud_cache的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter云端缓存管理插件cloud_cache的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


cloud_cache 是一个用于 Flutter 的云端缓存管理插件,它可以帮助开发者轻松地管理云端数据的缓存,减少网络请求,提升应用的性能和用户体验。以下是如何使用 cloud_cache 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 cloud_cache 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  cloud_cache: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在你的 Flutter 应用中初始化 cloud_cache 插件。通常,你可以在 main.dart 文件中进行初始化:

import 'package:cloud_cache/cloud_cache.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 CloudCache
  await CloudCache.initialize(
    baseUrl: 'https://your-api-endpoint.com', // 你的API基础URL
    cacheDuration: Duration(days: 7), // 缓存持续时间
  );

  runApp(MyApp());
}

3. 使用缓存

cloud_cache 提供了简单易用的 API 来获取和缓存数据。以下是一些常见的使用场景:

获取数据并缓存

import 'package:cloud_cache/cloud_cache.dart';

Future<void> fetchData() async {
  try {
    // 使用 CloudCache 获取数据
    var data = await CloudCache.get(
      '/api/data', // API 路径
      fromJson: (json) => MyDataModel.fromJson(json), // 数据解析函数
    );

    // 使用数据
    print(data);
  } catch (e) {
    print('Error: $e');
  }
}

强制刷新缓存

如果你需要强制刷新缓存,可以使用 forceRefresh 参数:

var data = await CloudCache.get(
  '/api/data',
  fromJson: (json) => MyDataModel.fromJson(json),
  forceRefresh: true, // 强制刷新缓存
);

清除缓存

你可以清除特定路径的缓存,或者清除所有缓存:

// 清除特定路径的缓存
await CloudCache.clear('/api/data');

// 清除所有缓存
await CloudCache.clearAll();

4. 处理缓存策略

cloud_cache 允许你自定义缓存策略。例如,你可以根据不同的 API 路径设置不同的缓存时间:

await CloudCache.initialize(
  baseUrl: 'https://your-api-endpoint.com',
  cacheDuration: Duration(days: 7),
  cachePolicies: {
    '/api/data': Duration(days: 1), // 特定路径的缓存时间
    '/api/other-data': Duration(hours: 12),
  },
);

5. 错误处理

cloud_cache 会自动处理网络错误和缓存错误。你可以通过 try-catch 来捕获和处理这些错误:

try {
  var data = await CloudCache.get(
    '/api/data',
    fromJson: (json) => MyDataModel.fromJson(json),
  );
} on CloudCacheException catch (e) {
  print('Cache error: ${e.message}');
} catch (e) {
  print('Unexpected error: $e');
}

6. 高级用法

cloud_cache 还支持更高级的用法,例如自定义缓存存储、监听缓存状态等。你可以参考插件的官方文档来了解更多细节。

7. 示例代码

以下是一个完整的示例代码,展示了如何使用 cloud_cache 插件:

import 'package:flutter/material.dart';
import 'package:cloud_cache/cloud_cache.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  await CloudCache.initialize(
    baseUrl: 'https://your-api-endpoint.com',
    cacheDuration: Duration(days: 7),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Cloud Cache Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: fetchData,
            child: Text('Fetch Data'),
          ),
        ),
      ),
    );
  }

  Future<void> fetchData() async {
    try {
      var data = await CloudCache.get(
        '/api/data',
        fromJson: (json) => MyDataModel.fromJson(json),
      );
      print(data);
    } catch (e) {
      print('Error: $e');
    }
  }
}

class MyDataModel {
  final String name;
  final int age;

  MyDataModel({required this.name, required this.age});

  factory MyDataModel.fromJson(Map<String, dynamic> json) {
    return MyDataModel(
      name: json['name'],
      age: json['age'],
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!