I am trying to save json response from api to the device. Right now I am making a text file and whenever I am calling the api, I am overwriting text file to save the response. And whenever offline or any sort of issue, I am returning the response from file. Question is, should I be doing this? If not, what would be a better alternative?
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));
}
}
}
}
Here's my file read and write function:
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);
}
}