Flutter缓存管理插件vyuh_cache的使用

Flutter缓存管理插件vyuh_cache的使用

Vyuh Logo

Vyuh Framework

构建模块化、可扩展、CMS驱动的Flutter应用程序

文档 | 官方网站

Vyuh Cache 💾

vyuh_cache

Vyuh框架的应用程序轻量级、灵活的缓存解决方案。提供基于时间的缓存,并支持可插拔的存储后端。非常适合减少API调用、提高应用性能和管理临时数据。

功能 ✨

  • 基于时间的缓存:自动过期(TTL) ⏱️
  • 类型安全:泛型实现以确保类型安全 🛡️
  • 可插拔存储:内置内存存储,具有可扩展的存储接口 💾
  • 异步API:所有操作均支持异步操作 ⚡
  • 值生成:内置支持生成缺失的缓存值 🔄
  • 过期处理:自动清理已过期条目 🧹

安装 📦

在`pubspec.yaml`文件中添加以下依赖:
dependencies:
  vyuh_cache: any

使用 💡

基本使用

创建一个带有内存存储的缓存实例:
// 创建一个带有内存存储的缓存实例
final cache = Cache(
  CacheConfig(
    storage: MemoryCacheStorage<String>(),
    ttl: Duration(minutes: 5),
  ),
);

// 存储一个值
await cache.set('greeting', 'Hello, World!');

// 检查键是否存在
if (await cache.has('greeting')) {
  // 获取值
  final value = await cache.get('greeting');
  print(value); // Hello, World!
}

值生成

获取值并自动生成缺失的值:
// 获取值并自动生成缺失的值
final value = await cache.build(
  'user-123',
  generateValue: () async {
    // 耗时操作(例如API调用)
    return await fetchUserFromApi('123');
  },
);

缓存管理

删除特定条目:
// 删除特定条目
await cache.remove('old-key');

清空所有条目:

// 清空所有条目
await cache.clear();

自定义存储

实现`CacheStorage`接口以支持自定义存储后端:
class RedisStorage<T> implements CacheStorage<T> {
  @override
  Future<CacheEntry<T>?> get(String key) async {
    // 实现Redis的get方法
  }

  @override
  Future<void> set(String key, CacheEntry<T> value) async {
    // 实现Redis的set方法
  }

  // ... 实现其他方法
}

最佳实践 🎯

  1. 选择合适的TTL:根据数据波动性设置TTL
  2. 错误处理:始终处理潜在的缓存未命中
  3. 类型安全:使用特定类型而不是动态类型
  4. 内存管理:清除未使用的缓存条目
  5. 存储选择:根据使用场景选择适当的存储方式

了解更多 📚


Vyuh 制作❤️

示例代码

// ignore_for_file: avoid_print

import 'dart:async';

import 'package:vyuh_cache/vyuh_cache.dart';

// 模拟API客户端
class ApiClient {
  Future<String> fetchUserData(String id) async {
    // 模拟API延迟
    await Future.delayed(const Duration(seconds: 1));
    return 'User data for ID: $id';
  }

  Future<Map<String, dynamic>> fetchProductDetails(String productId) async {
    await Future.delayed(const Duration(milliseconds: 800));
    return {
      'id': productId,
      'name': 'Product $productId',
      'price': 99.99,
    };
  }
}

void main() async {
  // 初始化API客户端
  final apiClient = ApiClient();

  // 示例1:基本字符串缓存
  print('\n=== 基本字符串缓存示例 ===');
  final stringCache = Cache(
    CacheConfig(
      storage: MemoryCacheStorage<String>(),
      ttl: const Duration(minutes: 5),
    ),
  );

  // 存储并检索简单的字符串
  await stringCache.set('greeting', 'Hello, World!');
  if (await stringCache.has('greeting')) {
    final greeting = await stringCache.get('greeting');
    print('缓存问候语: $greeting');
  }

  // 示例2:带自动生成功能的用户数据缓存
  print('\n=== 带自动生成功能的用户数据缓存示例 ===');
  final userCache = Cache(
    CacheConfig(
      storage: MemoryCacheStorage<String>(),
      ttl: const Duration(minutes: 10),
    ),
  );

  // 函数演示多次请求
  Future<void> getUserData(String userId) async {
    final userData = await userCache.build(
      'user-$userId',
      generateValue: () => apiClient.fetchUserData(userId),
    );
    print(
        '用户数据 (来自${await userCache.has('user-$userId') ? '缓存' : 'API'}): $userData');
  }

  // 第一次请求 - 将从API获取
  await getUserData('123');
  // 第二次请求 - 将从缓存获取
  await getUserData('123');

  // 示例3:复杂对象缓存(Map)
  print('\n=== 复杂对象缓存示例 ===');
  final productCache = Cache(
    CacheConfig(
      storage: MemoryCacheStorage<Map<String, dynamic>>(),
      ttl: const Duration(minutes: 15),
    ),
  );

  // 获取并缓存产品详情
  final productId = 'PROD-001';
  final productDetails = await productCache.build(
    'product-$productId',
    generateValue: () => apiClient.fetchProductDetails(productId),
  );

  print('产品详情: $productDetails');

  // 示例4:缓存管理
  print('\n=== 缓存管理示例 ===');

  // 列出字符串缓存中的所有键
  final keys = await stringCache.config.storage.keys();
  print('字符串缓存中的当前键: $keys');

  // 移除特定条目
  await stringCache.remove('greeting');
  print(
      '移除问候语后 - 是否存在: ${await stringCache.has('greeting')}');

  // 清空整个缓存
  await stringCache.clear();
  print(
      '清空后 - 键的数量: ${(await stringCache.config.storage.keys()).length}');

  // 示例5:错误处理
  print('\n=== 错误处理示例 ===');
  try {
    await userCache.build(
      'error-user',
      generateValue: () => throw Exception('无法获取用户数据'),
    );
  } catch (e) {
    print('处理错误: $e');
  }

  // 示例6:TTL演示
  print('\n=== TTL演示 ===');
  final shortCache = Cache(
    CacheConfig(
      storage: MemoryCacheStorage<String>(),
      ttl: const Duration(seconds: 2), // 用于演示的极短TTL
    ),
  );

  await shortCache.set('quick-value', '这将很快过期');
  print('初始值是否存在: ${await shortCache.has('quick-value')}');

  await Future.delayed(const Duration(seconds: 3));
  print(
      'TTL到期后 - 值是否存在: ${await shortCache.has('quick-value')}');
}

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

1 回复

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


当然,以下是关于如何使用Flutter缓存管理插件vyuh_cache的一个示例。这个示例将展示如何在Flutter应用中集成并使用vyuh_cache来进行缓存管理。

首先,你需要在你的pubspec.yaml文件中添加vyuh_cache依赖:

dependencies:
  flutter:
    sdk: flutter
  vyuh_cache: ^最新版本号 # 请替换为实际发布的最新版本号

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

接下来,我们来看一个如何使用vyuh_cache的示例。假设我们有一个API调用,我们想要缓存其响应数据以减少网络请求。

  1. 导入vyuh_cache

在你的Dart文件中导入vyuh_cache

import 'package:vyuh_cache/vyuh_cache.dart';
  1. 配置缓存

在你的应用中配置缓存。通常,这可以在应用初始化时完成:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 配置vyuh_cache
  await VyuhCache.init(
    cacheDuration: const Duration(hours: 1), // 设置缓存持续时间
    storage: await VyuhCacheStorage.diskStorage(
      directory: (await getApplicationDocumentsDirectory()).path,
    ),
  );

  runApp(MyApp());
}
  1. 使用缓存进行API调用

假设我们有一个简单的API调用函数,我们可以使用vyuh_cache来缓存其响应:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Map<String, dynamic>> fetchData(String url) async {
  // 尝试从缓存中获取数据
  final cachedData = await VyuhCache.get(url);
  if (cachedData != null) {
    return jsonDecode(cachedData) as Map<String, dynamic>;
  }

  // 如果缓存中没有数据,则进行网络请求
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    // 将数据保存到缓存中
    await VyuhCache.put(url, jsonEncode(response.body));
    return jsonDecode(response.body) as Map<String, dynamic>;
  } else {
    throw Exception('Failed to load data');
  }
}
  1. 在UI中使用

在你的Flutter组件中调用上述fetchData函数:

import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await VyuhCache.init(
    cacheDuration: const Duration(hours: 1),
    storage: await VyuhCacheStorage.diskStorage(
      directory: (await getApplicationDocumentsDirectory()).path,
    ),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DataFetcher(),
    );
  }
}

class DataFetcher extends StatefulWidget {
  @override
  _DataFetcherState createState() => _DataFetcherState();
}

class _DataFetcherState extends State<DataFetcher> {
  Map<String, dynamic>? data;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    fetchDataAndUpdateUI('https://api.example.com/data');
  }

  Future<void> fetchDataAndUpdateUI(String url) async {
    try {
      setState(() {
        isLoading = true;
      });
      data = await fetchData(url);
    } catch (error) {
      print('Error fetching data: $error');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Data Fetcher'),
      ),
      body: Center(
        child: isLoading
            ? CircularProgressIndicator()
            : ListView.builder(
                itemCount: data?.length ?? 0,
                itemBuilder: (context, index) {
                  final key = data!.keys.elementAt(index);
                  final value = data![key];
                  return ListTile(
                    title: Text("$key: $value"),
                  );
                },
              ),
      ),
    );
  }
}

这个示例展示了如何使用vyuh_cache来缓存API响应数据,并在Flutter应用中展示这些数据。注意,你需要根据你的实际需求调整缓存持续时间、存储位置以及API URL等参数。

回到顶部