所以按照评论并阅读flutter persistence cookbook,我看到了三种常见的可能性:
- 使用 SQLite 持久化数据
- 读写文件
- 在磁盘上存储键值数据
每个都有不同的用例,但我认为常见的情况是将一些对象存储为 JSON。在我看来,SQLite 在简单的情况下有点矫枉过正,而且键值不能提供足够的灵活性。所以我会关注reading and writing files。
这里有一个例子。我使用 JSON 代码生成库作为described here。
我读写到磁盘的数据对象如下所示:
import 'package:json_annotation/json_annotation.dart';
// json methods generated using code geneartion
// see https://flutter.dev/docs/development/data-and-backend/json#serializing-json-using-code-generation-libraries
part 'easy_data.g.dart';
@JsonSerializable()
class EasyData {
int counter;
String data;
EasyData(this.counter, this.data);
// run the following command to generate json:
// flutter pub run build_runner build
factory EasyData.fromJson(Map<String, dynamic> json) => _$EasyDataFromJson(json);
Map<String, dynamic> toJson() => _$EasyDataToJson(this);
}
从磁盘加载 json 并保存的服务如下所示:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import '../model/easy_data.dart';
class FileStorage with ChangeNotifier {
EasyData loadedData;
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/app_data.json');
}
loadData() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
if (contents != null) {
// parse json if file was saved before
loadedData = EasyData.fromJson(json.decode(contents));
notifyListeners();
}
} on FileSystemException catch (_) {
// the file did not exist before
} catch (e) {
// error handling
log(e);
}
}
Future<File> writeData(EasyData data) async {
final file = await _localFile;
// Write the file
return file.writeAsString(jsonEncode(data.toJson()));
}
}
我为服务使用了provider,因为我希望在从磁盘加载数据时通知其他服务。其他 Provider 需要在 main dart 中用 ChangeNotifierProxyProvider 声明,才能使用来自 FileStorage Provider 的信息。
希望对你有所帮助。