Flutter本地存储缓存插件local_storage_cache的使用

Flutter本地存储缓存插件local_storage_cache的使用

特性

  • 数据存储:使用共享偏好保存和检索不同类型的数据(String, int, bool, double, JSON)。
  • 加密:在保存前自动加密数据,并在检索时解密以确保安全。
  • 缓存管理:使用SQLite缓存数据并设置可选的TTL(过期时间),使数据在设定的时间后过期。
  • 数据移除:从本地存储和缓存中删除特定数据或清除所有数据。
  • 备份和恢复:备份和恢复本地存储和缓存中的数据,便于数据迁移和恢复。
  • 过期通知:当缓存数据过期时调用回调函数。

安装

在你的包的pubspec.yaml文件中添加以下内容:

dependencies:
  local_storage_cache:
    git:
      url: https://github.com/protheeuz/local_storage_cache.git
      ref: main

运行 flutter pub get 来安装它。

使用

本地存储

import 'package:local_storage_cache/local_storage_cache.dart';

final localStorage = LocalStorage();

// 保存数据
await localStorage.saveString('key1', 'value1');

// 检索数据
final value = await localStorage.getString('key1');
print(value); // 输出: value1

// 保存其他类型的数据
await localStorage.saveInt('key2', 123);
await localStorage.saveBool('key3', true);
await localStorage.saveDouble('key4', 1.23);
await localStorage.saveJson('key5', {'field': 'value'});

// 检索其他类型的数据
final intValue = await localStorage.getInt('key2');
final boolValue = await localStorage.getBool('key3');
final doubleValue = await localStorage.getDouble('key4');
final jsonValue = await localStorage.getJson('key5');

// 删除数据
await localStorage.removeData('key1');

// 清除所有数据
await localStorage.clearAll();

缓存管理器

import 'package:local_storage_cache/local_storage_cache.dart';

final cacheManager = CacheManager(expirationCallback: (key) {
  print('缓存已过期,键为: $key');
});

// 保存缓存
await cacheManager.saveCache('key1', 'value1');

// 检索缓存
final value = await cacheManager.getCache('key1');
print(value); // 输出: value1

// 保存带TTL的缓存
await cacheManager.saveCache('key2', 'value2', ttl: Duration(seconds: 5));

// 在过期前检索缓存
final valueBeforeExpiration = await cacheManager.getCache('key2');
print(valueBeforeExpiration); // 输出: value2

// 等待TTL过期
await Future.delayed(Duration(seconds: 6));

// 在过期后检索缓存
final valueAfterExpiration = await cacheManager.getCache('key2');
print(valueAfterExpiration); // 输出: null

// 删除缓存
await cacheManager.removeCache('key1');

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

// 备份缓存
await cacheManager.backupCache('/path/to/backup.json');

// 恢复缓存
await cacheManager.restoreCache('/path/to/backup.json');

其他注意事项

在使用备份和恢复功能时,请确保将/path/to/backup.json替换为你文件系统中的适当路径。你可以根据实现的额外功能添加更多示例和文档。


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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用local_storage_cache插件进行本地存储缓存的示例代码。

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

dependencies:
  flutter:
    sdk: flutter
  local_storage_cache: ^0.x.x  # 请注意使用最新版本号

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

接下来是具体的代码示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Local Storage Cache Example'),
        ),
        body: CacheExample(),
      ),
    );
  }
}

class CacheExample extends StatefulWidget {
  @override
  _CacheExampleState createState() => _CacheExampleState();
}

class _CacheExampleState extends State<CacheExample> {
  final LocalStorageCache localStorageCache = LocalStorageCache();

  String cachedData = '';

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          Text('Cached Data:'),
          Text(cachedData),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () async {
              // 模拟数据写入缓存
              String dataToWrite = 'Hello, Flutter Local Storage Cache!';
              await localStorageCache.setItem('myKey', dataToWrite);

              // 从缓存读取数据
              String dataRead = await localStorageCache.getItem('myKey');

              // 更新状态
              setState(() {
                cachedData = dataRead;
              });
            },
            child: Text('Write and Read Cache'),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: async () {
              // 从缓存删除数据
              await localStorageCache.removeItem('myKey');

              // 更新状态
              setState(() {
                cachedData = 'Data Removed';
              });

              // 延迟1秒再次读取以确认数据已被删除
              Future.delayed(Duration(seconds: 1), () async {
                String dataRead = await localStorageCache.getItem('myKey');
                setState(() {
                  cachedData = dataRead ?? 'No Data Found';
                });
              });
            },
            child: Text('Remove Cache'),
          ),
        ],
      ),
    );
  }
}

解释

  1. 依赖添加

    • pubspec.yaml文件中添加local_storage_cache依赖。
  2. 创建UI

    • 使用MaterialAppScaffold来创建应用的基本结构。
    • 使用ColumnText组件来显示缓存的数据。
    • 使用ElevatedButton组件来触发缓存的写入、读取和删除操作。
  3. 状态管理

    • 使用StatefulWidget_CacheExampleState来管理缓存数据的状态。
    • 通过setState方法来更新UI以反映缓存数据的变化。
  4. 缓存操作

    • 使用LocalStorageCachesetItem方法将数据写入缓存。
    • 使用getItem方法从缓存读取数据。
    • 使用removeItem方法从缓存删除数据。

这样,你就可以在Flutter应用中使用local_storage_cache插件进行本地存储缓存操作了。

回到顶部