Flutter缓存管理插件ever_cache的使用

Flutter缓存管理插件ever_cache的使用

🚀 EverCache

Pub Version
Dart Flutter

✨ 关键特性 #

  • 🚀 延迟初始化: 在首次访问时才计算缓存项。(或手动触发计算!)
  • ⏳ TTL 支持: 在设定的时间后自动清除缓存项。
  • 📡 事件: 监控基于实例调用委托的缓存状态。
  • 🔧 占位符: 提供占位数据,在计算过程中返回默认值。
  • 🔍 访问锁定: 使用 `lock` 功能控制对计算值的访问。

🚀 开始使用 #

将 `ever_cache` 轻松集成到你的项目中。只需在 `pubspec.yaml` 中添加以下内容:
dependencies:
  ever_cache: ^0.0.8

然后运行 pub getflutter pub get

🌟 使用示例 #

import 'package:ever_cache/ever_cache.dart';

final cache = EverCache<String>(
    () async {
        // Your computation

        return 'Hello, World!';
    },
    // 设置一个占位符,当你希望在计算进行中返回默认值时。
    placeholder: () => 'placeholder',
    // 设置缓存条目的 TTL(生存时间)。
    ttl: EverTTL.seconds(5),
    // 如果你想监控从缓存发出的不同事件。
    events: EverEvents(
        onComputing: () => print('正在计算...'),
        onComputed: () => print('计算完成!'),
        onInvalidated: () => print('已失效!'),
        onError: (e, stackTrace) => print('出错!计算失败: $e'),
    ),
    // 如果你希望在构造函数被调用时立即在后台计算缓存。
    earlyCompute: true,
);

// 访问计算后的值
// cache.value
// 或者为了安全地访问它,使用 cache.state

📚 其他方法 #

  • compute(): 手动异步计算缓存条目。
  • computeSync(): 手动同步计算缓存条目。
  • lock(): 锁定缓存条目以防止进一步访问,直到提供的回调被执行。
  • invalidate(): 使缓存条目失效。
  • dispose(): 处置缓存条目。

注意 #

EverCache 是一个开源项目,欢迎贡献!如果你遇到任何问题或有功能请求,请在项目的 issue 追踪器中提交。

对于更详细的文档,请参阅 lib/ 目录中的源代码和注释。

完整示例 Demo

// ignore_for_file: avoid_print

import 'package:ever_cache/ever_cache.dart';

void main() {
  final cache = EverCache<String>(
    () async {
      await Future.delayed(const Duration(seconds: 1));
      return 'test';
    },
    placeholder: () => 'placeholder',
    events: EverEvents(
      onComputing: () => print('正在计算...'),
      onComputed: () => print('计算完成!'),
    ),
    earlyCompute: true,
  );

  print(cache.value);
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用ever_cache插件进行缓存管理的示例代码。ever_cache是一个用于缓存数据的Flutter插件,它可以帮助开发者在本地存储数据,以便在离线时访问或加速数据加载。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  ever_cache: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

2. 导入包

在你的Dart文件中导入ever_cache包:

import 'package:ever_cache/ever_cache.dart';

3. 初始化EverCache实例

创建一个EverCache实例。你可以根据需求设置缓存的大小和过期时间等参数。

final EverCache<String, String> cache = EverCache<String, String>(
  storage: EverCacheStorage.MEMORY, // 可以选择MEMORY或DISK
  capacity: 100, // 缓存容量
  expireDuration: Duration(days: 7), // 缓存过期时间
);

4. 使用缓存

添加数据到缓存

void addDataToCache() async {
  String key = "exampleKey";
  String value = "exampleValue";
  
  bool isSuccess = await cache.put(key, value);
  if (isSuccess) {
    print("Data added to cache successfully.");
  } else {
    print("Failed to add data to cache.");
  }
}

从缓存中获取数据

void getDataFromCache() async {
  String key = "exampleKey";
  
  EverCacheResult<String?> result = await cache.get(key);
  if (result.isHit) {
    print("Data retrieved from cache: ${result.value}");
  } else {
    print("Cache miss, data not found.");
    // 处理缓存未命中的情况,例如从网络获取数据
  }
}

删除缓存中的数据

void removeDataFromCache() async {
  String key = "exampleKey";
  
  bool isSuccess = await cache.evict(key);
  if (isSuccess) {
    print("Data removed from cache successfully.");
  } else {
    print("Failed to remove data from cache.");
  }
}

清空整个缓存

void clearCache() async {
  bool isSuccess = await cache.clear();
  if (isSuccess) {
    print("Cache cleared successfully.");
  } else {
    print("Failed to clear cache.");
  }
}

5. 完整示例

以下是一个完整的示例,展示了如何使用ever_cache插件进行基本的缓存管理操作:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final EverCache<String, String> cache = EverCache<String, String>(
    storage: EverCacheStorage.MEMORY,
    capacity: 100,
    expireDuration: Duration(days: 7),
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('EverCache Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  await addDataToCache();
                },
                child: Text('Add Data to Cache'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await getDataFromCache();
                },
                child: Text('Get Data from Cache'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await removeDataFromCache();
                },
                child: Text('Remove Data from Cache'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await clearCache();
                },
                child: Text('Clear Cache'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> addDataToCache() async {
    String key = "exampleKey";
    String value = "exampleValue";
    
    bool isSuccess = await cache.put(key, value);
    if (isSuccess) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Data added to cache successfully.")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Failed to add data to cache.")));
    }
  }

  Future<void> getDataFromCache() async {
    String key = "exampleKey";
    
    EverCacheResult<String?> result = await cache.get(key);
    if (result.isHit) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Data retrieved from cache: ${result.value}")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Cache miss, data not found.")));
    }
  }

  Future<void> removeDataFromCache() async {
    String key = "exampleKey";
    
    bool isSuccess = await cache.evict(key);
    if (isSuccess) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Data removed from cache successfully.")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Failed to remove data from cache.")));
    }
  }

  Future<void> clearCache() async {
    bool isSuccess = await cache.clear();
    if (isSuccess) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Cache cleared successfully.")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Failed to clear cache.")));
    }
  }
}

这个示例展示了如何在Flutter应用中使用ever_cache插件来添加、获取、删除和清空缓存数据。你可以根据实际需求进行进一步的修改和扩展。

回到顶部