I fetch data and I tried to use cache in order for my app to be faster if same data comes.
So I asked this question and get answer that I need to use package dio_cache_interceptor
.
So I use it as below.
final cacheOptions = CacheOptions(
// A default store is required for interceptor.
store: MemCacheStore(),
// All subsequent fields are optional.
// Default.
policy: CachePolicy.forceCache,
// Returns a cached response on error but for statuses 401 & 403.
// Also allows to return a cached response on network errors (e.g. offline usage).
// Defaults to [null].
hitCacheOnErrorExcept: [401, 403],
// Overrides any HTTP directive to delete entry past this duration.
// Useful only when origin server has no cache config or custom behaviour is desired.
// Defaults to [null].
maxStale: const Duration(days: 2),
// Default. Allows 3 cache sets and ease cleanup.
priority: CachePriority.high,
// Default. Body and headers encryption with your own algorithm.
cipher: null,
// Default. Key builder to retrieve requests.
keyBuilder: (request) {
return request.uri.toString();
},
// Default. Allows to cache POST requests.
// Overriding [keyBuilder] is strongly recommended when [true].
allowPostMethod: true,
);
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 dio = Dio()
..interceptors.add(DioCacheInterceptor(options: cacheOptions));
final response = await dio.post(
"https://diejlcrtffmlsdyvcagq.supabase.co/functions/~~~",
data: requestBodyJson,
options: cacheOptions.copyWith(policy: CachePolicy.refresh).toOptions(),
// headers: headers,
);
if (response.statusCode == 200) {
// final data = jsonDecode(utf8.decode(response.data));
final data = response.data["data"];
return data;
}
} catch (e) {
// ignore: avoid_print
print("fetchTotalDiaries --> $e");
}
return [];
}
But after I fetch this data initially, I fetch this once again as data is not changed, it takes same time to fetch it.
My goal is to make it faster when I tried to fetch it once again and as I see Instagram, It works as I expected.
Please give me some advice on this.