How to cache POST requests without dio in Flutter?

624

I used both flutter_cache_manager along with http.post method to attain this.

Below is the method which I tried and is now working fine.

Note: Make sure the finalUrl in the below has a unique url for the each change of header/params which has to be generated on your logic.

String finalUrl = 'some unique url';
String tempResponse = '';
// checks if the file exists in cache
var fileInfo = await DefaultCacheManager().getFileFromCache(finalUrl);
if (fileInfo == null) {
  // get data from online if not present in cache
  http.Response response;
  try {
    var response = await http.post(url, headers: header, body: _body);;
  } catch (e) {
    print(e);
  }
  tempResponse = response.body;

  // put data into cache after getting from internet
  List<int> list = tempResponse.codeUnits;
  Uint8List fileBytes = Uint8List.fromList(list);
  DefaultCacheManager().putFile(finalUrl, fileBytes);
} else {
  // get data from file if present in cache
  tempResponse = fileInfo.file.readAsStringSync();
}
var result = json.decode(tempResponse);
Share:
624
Vitor
Author by

Vitor

Updated on December 22, 2022

Comments

  • Vitor
    Vitor over 1 year

    I'm trying to cache some API calls but so far I couldn't find the best/most optimal way of doing this. I'm not interested in using Dio for this since I have a lot of API calls that I need to cache.

    Also, I tried using async_resource which seemed to be a really simple plugin to use but it's not compatible with flutter_google_places which I'm using in my project.

    I took a look at flutter_cache_manager but I didn't find any example with POST calls.

    So, this is how I'm doing the API calls:

    var url = 'www.my-url.com/api';
    
    var header = {
      "Content-type": "application/json",
      "key": "my-key",
      "token": "my-token"
    };
    
    var params = {
      "limit": limit,
      "page": page,
    };
    
    var _body = json.encode(params);
    
    try {
      var response = await http.post(url, headers: header, body: _body);
      return json.decode(response.body);
    } catch (e) {
      return null;
    }
    

    How should I cache this data?