1
votes

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);
  }
}
2
rather than try catching to return a null value, use file exists, i suppose you are doing alright with the cachingYadu

2 Answers

1
votes

Well I would suggest you to use shared_preferences it is easy to store and cache favourite items and few stuff like when we have to use dark or light mode. So you can also save json objects and it is quiet easy and simple. So you dont have to create a text file everytime.

First what you have to do is get the package in the pubspec then

import 'package:shared_preferences/shared_preferences.dart';

SharedPreferences prefs = await SharedPreferences.getInstance();

Now to save the json data you have to do is

prefs.setString('mydata', json.encode(yourjsondata));

to retrieve this data you must use the exact name you assigned , in my case 'mydata'

json.decode(preferences.getString('mydata'))

Done this is all it is everything. Well thanks to you I got this idea while reading your proposed problem. Hope this would help : )

0
votes

Use package cached_map this is simplest way of storing json , it is developed by me

await Mapped.saveFilesDirectly(file:{"user name":"user","email":"[email protected]"},
cachedFileName: "user");

Map<String, dynamic>? user = await Mapped.loadFileDirectly(cachedFileName: "user");

Mapped.deleteFileDirectly(cachedFileName: "user");