思路
- 引入依赖:在
pubspec.yaml
文件中添加dio
和dio_cache_interceptor
依赖,dio_cache_interceptor
用于实现缓存功能。
- 配置缓存策略:根据不同请求的缓存要求,创建不同的缓存策略。例如,对于缓存时间长的数据,设置较长的缓存有效期;对于实时性要求高的数据,设置较短的缓存有效期或不使用缓存。
- 使用Dio发送请求:通过
Dio
实例发送不同类型的网络请求,并根据缓存策略应用相应的缓存配置。
关键代码片段
- 添加依赖:
dependencies:
dio: ^4.0.0
dio_cache_interceptor: ^4.0.0
- 初始化Dio并配置缓存:
import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
// 创建缓存策略
final cacheOptions = CacheOptions(
// 缓存存储,这里使用默认的内存和磁盘存储
store: DefaultCacheStore(),
// 缓存有效期,例如长时间缓存数据设置为1小时
maxStale: const Duration(hours: 1),
// 清除缓存时间间隔
priority: CachePriority.normal,
// 缓存命中率统计
hitCacheOnErrorExcept: [401, 403],
// 缓存响应内容类型
keys: ['*'],
// 缓存控制
options: CacheOptions.defaultCacheOptions,
);
// 创建Dio实例并添加缓存拦截器
final dio = Dio()
..interceptors.add(
DioCacheInterceptor(options: cacheOptions),
);
- 发送不同类型请求并应用缓存:
// GET请求,使用缓存策略
Future<Response> getRequestWithCache() async {
try {
final response = await dio.get('/your_api_endpoint');
return response;
} catch (e) {
print('Error: $e');
rethrow;
}
}
// POST请求,实时性要求高,不使用缓存(可以通过设置maxStale为0来实现)
Future<Response> postRequestWithoutCache() async {
final cacheOptionsNoCache = CacheOptions(
store: DefaultCacheStore(),
maxStale: Duration.zero,
priority: CachePriority.normal,
hitCacheOnErrorExcept: [401, 403],
keys: ['*'],
options: CacheOptions.defaultCacheOptions,
);
final dioWithNoCache = Dio()
..interceptors.add(
DioCacheInterceptor(options: cacheOptionsNoCache),
);
try {
final response = await dioWithNoCache.post('/your_api_endpoint', data: {'key': 'value'});
return response;
} catch (e) {
print('Error: $e');
rethrow;
}
}