Flutter数据缓存插件eyf_cache的使用

Flutter数据缓存插件eyf_cache的使用

1、 MMKV本地数据缓存

MMKVStorage 是一个用于本地数据缓存的工具类,支持多种数据类型的存储和读取。

/// 保存int数据
/// [key] 存储key
/// [value] int value
MMKVStorage.instance.putInt({required String key, int value = 0});

/// 保存double数据
/// [key] 存储key
/// [value] double value
MMKVStorage.instance.putDouble({required String key, double value = 0.0});

/// 保存string数据
/// [key] 存储key
/// [value] string value
MMKVStorage.instance.putString({required String key, String value = ""});

/// 保存动态数据
/// [key] 存储key
/// [data] dynamic data
MMKVStorage.instance.put({required String key, dynamic data});

/// 获取int值
/// [key] 存储key
Future<int?> getInt(String key) async {
  return await MMKVStorage.instance.getInt(key);
}

/// 获取double值
/// [key] 存储key
Future<double?> getDouble(String key) async {
  return await MMKVStorage.instance.getDouble(key);
}

/// 获取bool值
/// [key] 存储key
Future<bool?> getBool(String key) async {
  return await MMKVStorage.instance.getBool(key);
}

/// 获取string值
/// [key] 存储key
Future<String?> getString(String key) async {
  return await MMKVStorage.instance.getString(key);
}

/// 获取存储对象
/// [key] 存储key
Future<T?> getEntity<T>(String key) async {
  return await MMKVStorage.instance.getEntity<T>(key);
}

/// 获取存储列表
/// [key] 存储key
Future<T?> getList<T>(String key) async {
  return await MMKVStorage.instance.getList<T>(key);
}

/// 清除key对应缓存数据
/// [key] 存储key
void remove(String key) {
  MMKVStorage.instance.remove(key);
}

2、特定时间内的数据缓存

EffectiveStorage 是一个用于特定时间内数据缓存的工具类,支持设置缓存的有效期。

/// 缓存有效数据
/// [cacheKey] 缓存key
/// [value] 缓存数据
/// [duration] 缓存时间
Future<void> putString({
  required String cacheKey,
  required String value,
  Duration duration = const Duration(hours: 1),
}) async {
  return await EffectiveStorage.instance.putString(
    cacheKey: cacheKey,
    value: value,
    duration: duration,
  );
}

/// 清除缓存
/// [cacheKey] 缓存key
void clean(String cacheKey) {
  EffectiveStorage.instance.clean(cacheKey);
}

/// 获取有效数据
/// [cacheKey] 缓存key
Future<String> getString(String cacheKey) async {
  return await EffectiveStorage.instance.getString(cacheKey);
}

示例代码

以下是一个完整的示例代码,展示如何使用 eyf_cache 插件进行数据缓存。

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _cachedValue = "未加载";

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化时从缓存中获取数据
    _loadCachedData();
  }

  Future<void> _loadCachedData() async {
    final value = await EffectiveStorage.instance.getString("testCacheKey");
    setState(() {
      _cachedValue = value ?? "缓存为空";
    });
  }

  Future<void> _saveToCache() async {
    // 将数据保存到缓存中,并设置有效期为1小时
    await EffectiveStorage.instance.putString(
      cacheKey: "testCacheKey",
      value: "Hello, eyf_cache!",
      duration: const Duration(hours: 1),
    );
    _loadCachedData(); // 刷新页面以显示新数据
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("eyf_cache 示例"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("缓存值: $_cachedValue"),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _saveToCache,
              child: Text("保存到缓存"),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


eyf_cache 是一个用于 Flutter 应用的数据缓存插件,它可以帮助你轻松地在本地存储和检索数据。以下是如何使用 eyf_cache 插件的基本步骤:

1. 添加依赖

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

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

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

2. 初始化缓存

在使用 eyf_cache 之前,你需要初始化缓存。通常,你可以在应用的 main 函数中进行初始化:

import 'package:eyf_cache/eyf_cache.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EyfCache.init();  // 初始化缓存
  runApp(MyApp());
}

3. 存储数据

你可以使用 EyfCache 来存储数据。eyf_cache 支持存储字符串、整数、布尔值、列表和 Map 等数据类型。

// 存储字符串
await EyfCache.setString('key1', 'Hello, World!');

// 存储整数
await EyfCache.setInt('key2', 42);

// 存储布尔值
await EyfCache.setBool('key3', true);

// 存储列表
await EyfCache.setList('key4', [1, 2, 3]);

// 存储 Map
await EyfCache.setMap('key5', {'name': 'John', 'age': 30});

4. 检索数据

你可以使用 EyfCache 来检索之前存储的数据:

// 检索字符串
String? stringValue = await EyfCache.getString('key1');

// 检索整数
int? intValue = await EyfCache.getInt('key2');

// 检索布尔值
bool? boolValue = await EyfCache.getBool('key3');

// 检索列表
List<dynamic>? listValue = await EyfCache.getList('key4');

// 检索 Map
Map<String, dynamic>? mapValue = await EyfCache.getMap('key5');

5. 删除数据

你可以使用 EyfCache 来删除缓存中的数据:

await EyfCache.remove('key1');  // 删除指定键的数据
await EyfCache.clear();         // 清除所有缓存数据

6. 检查缓存中是否存在某个键

你可以检查缓存中是否存在某个键:

bool exists = await EyfCache.containsKey('key1');

7. 设置缓存过期时间

eyf_cache 还支持设置缓存数据的过期时间:

await EyfCache.setString('key1', 'Hello, World!', expireIn: Duration(minutes: 10));  // 10分钟后过期

8. 获取缓存大小

你可以获取当前缓存的大小:

int cacheSize = await EyfCache.getCacheSize();

9. 监听缓存变化

eyf_cache 还支持监听缓存的变化:

EyfCache.addListener('key1', (value) {
  print('key1 的值发生了变化: $value');
});

10. 移除监听器

你可以移除之前添加的监听器:

EyfCache.removeListener('key1');
回到顶部