-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathcustom_cache_interceptor.dart
More file actions
45 lines (38 loc) · 1.26 KB
/
custom_cache_interceptor.dart
File metadata and controls
45 lines (38 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import 'package:dio/dio.dart';
class CacheInterceptor extends Interceptor {
CacheInterceptor();
final _cache = <Uri, Response>{};
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
final response = _cache[options.uri];
if (options.extra['refresh'] == true) {
print('${options.uri}: force refresh, ignore cache! \n');
return handler.next(options);
} else if (response != null) {
print('cache hit: ${options.uri} \n');
return handler.resolve(response);
}
super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
_cache[response.requestOptions.uri] = response;
super.onResponse(response, handler);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
print('onError: $err');
super.onError(err, handler);
}
}
void main() async {
final dio = Dio();
dio.options.baseUrl = 'https://pub.dev';
dio.interceptors
..add(CacheInterceptor())
..add(LogInterceptor(requestHeader: false, responseHeader: false));
await dio.get('/'); // second request
await dio.get('/'); // Will hit cache
// Force refresh
await dio.get('/', options: Options(extra: {'refresh': true}));
}