flutter_async_storage
flutter_async_storage 从 Flutter 应用内部读取 React Native 的 AsyncStorage 数据。这对于已从 React Native 迁移到 Flutter 并需要访问存储在磁盘上的数据的应用程序非常有用。
读取数据
要在 Flutter 中从 AsyncStorage 读取数据,您可以使用类似以下的工作流程:
final asyncStorageReader = AsyncStorageReader(LocalPlatform());
try {
if (await asyncStorageReader.exists()) {
final data = await asyncStorageReader.data('myDataKey');
// Do something with data...
// Clear AsyncStorage.
await asyncStorageReader.clear();
}
} catch (e) {
// Handle error.
}
使用数据
AsyncStorage 中的数据是按键存储的;您可以使用 AsyncStorageReader 上的 data() 方法读取任意键。返回的数据是字符串化的 JSON,您可以将其反序列化为其他格式。 built_value 允许您创建自定义反序列化器,这有助于将数据转换为 Dart 对象。
特定平台代码
flutter_async_storage 可以读取 Android 和 iOS 上的 AsyncStorage 数据。在 Android 上,AsyncStorage 数据存储在 SQLite 数据库的 RKStorage 表中。在 iOS 上,AsyncStorage 数据存储在文件系统中(较小数据存储在清单文件中,较大数据使用哈希函数分片到单独的文件中)。flutter_async_storage 模仿了 React Native 的 AsyncStorage 检索数据的路径。
必须在 AsyncStorageReader 的构造函数中指定平台,但 API 保持不变。