1

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);
  }
}
1
  • rather than try catching to return a null value, use file exists, i suppose you are doing alright with the caching Commented Jul 16, 2020 at 11:29

2 Answers 2

2

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 : )

Sign up to request clarification or add additional context in comments.

2 Comments

I was doing this initially but I came across something that made me change my mind. Seems like it is not a good practice to store large strings on shared preferences as it can lead to issues.
I guess than using a lite database would be a go. like sqflite or hive
1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.