Search code examples
fluttercaching

Is there any way to cache http data as comparing existing cached data and new data in flutter?


I fetch data as using post request to supabase database in Flutter project as below.

Future<List> fetchTotalDiaries(
      UserProfile userProfile, int currentPage) async {
    try {
      Map<String, dynamic> requestBody = {
        'user': userProfile.toJson(),
        'currentPage': currentPage,
        'offset': offset,
      };

      String requestBodyJson = jsonEncode(requestBody);

      final response = await http.post(
        totalDiarygroupFunctionsUri,
        body: requestBodyJson,
        headers: headers,
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(utf8.decode(response.bodyBytes));
        return data["data"];
      }
    } catch (e) {
      // ignore: avoid_print
      print("fetchTotalDiaries --> $e");
    }

    return [];
  }

But I wanted to make app faster when fetching data, so I tried to use cache.

And I tried to use package flutter_cache_manager.

For example, I fetch data first time {"a": "hi", "b": "hi2", "c": "hi3"} as requesting from url www.abc.com.

Then I requesting once again www.abc.com, then It already has data, cache will returns existing data.

But what I want is that It request once again, and fetched data is changed like {"a": "hi", "b": "hi2", "c": "hi3", "d": "hi4" }

Then It change cached data as comparing existing data and new data.

Is there any way to do this?

I check that Instagram is also firstly takes long time but secondly takes shorter time and I guess It uses cache somehow even though Instagram's fetched data kept changed.

Please give me some advice.


Solution

  • I think what you are looking for is cache invalidation. Here you can find how to do it for flutter_cache_manager. Since you want to cache http calls, I suggest using dio_cache_interceptor as it can set the stale period automatically from an http response if the needed headers are included. See here for further information on http cache-control.