我正在尝试将来自api的json响应保存到设备。现在我正在制作一个文本文件,每当我调用api时,我都会覆盖文本文件以保存响应。无论何时离线或任何类型的问题,我都会从文件中返回响应。问题是,我应该这样做吗?如果不是,什么是更好的选择?
class EventRepository {
Future<EventResponse> getEvents({page}) async {
try {
var response = await apiCall.getData('events?page=$page&limit=10&q=');
var data = response.data;
if (page == 1) {
await CacheStorage().writeCache(jsonEncode(data), "events");
}
return EventResponse.fromJson(data, isCache: false);
} catch (error, stacktrace) {
var eventData;
print("Exception occured: $error stackTrace: $stacktrace");
var events = await CacheStorage().readCache("events");
if (events != null) {
eventData = json.decode(events);
return EventResponse.fromJson(eventData);
} else {
return EventResponse.withError(handleError(error));
}
}
}
}下面是我的文件读写函数:
class CacheStorage {
Future<String> readCache(String fileName) async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/$fileName.txt');
text = await file.readAsString();
} catch (e) {
text = null;
}
return text;
}
writeCache(String text, String path) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/$path.txt');
await file.writeAsString(text);
}
}发布于 2020-07-16 20:38:53
好吧,我建议你使用shared_preferences,它很容易存储和缓存喜爱的项目,并且很少有东西,比如当我们必须使用暗或亮模式时。所以你也可以保存json对象,而且非常简单。所以你不必每次都创建一个文本文件。
首先,您要做的是将包放入pubspec中,然后
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences prefs = await SharedPreferences.getInstance();现在,要保存json数据,您必须做的是
prefs.setString('mydata', json.encode(yourjsondata));要检索此数据,您必须使用指定的确切名称,在我的示例中为'mydata‘
json.decode(preferences.getString('mydata'))做这件事就是一切。多亏了你,我在阅读你提出的问题时有了这个想法。希望这能有所帮助:)
发布于 2021-06-30 18:55:09
使用包cached_map这是存储json的最简单的方式,它是由我开发的
await Mapped.saveFilesDirectly(file:{"user name":"user","email":"user@gmail.com"},
cachedFileName: "user");
Map<String, dynamic>? user = await Mapped.loadFileDirectly(cachedFileName: "user");
Mapped.deleteFileDirectly(cachedFileName: "user");https://stackoverflow.com/questions/62930221
复制相似问题