MST
星途 面试题库

面试题:Flutter使用dio实现复杂缓存场景处理

假设在一个Flutter应用中有不同类型的网络请求(如GET、POST等),且对不同请求有不同的缓存要求(部分数据缓存时间长,部分数据实时性要求高),请描述如何利用dio来实现这些复杂的缓存场景,需要给出具体实现的关键代码片段及思路。
10.7万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

思路

  1. 引入依赖:在pubspec.yaml文件中添加diodio_cache_interceptor依赖,dio_cache_interceptor用于实现缓存功能。
  2. 配置缓存策略:根据不同请求的缓存要求,创建不同的缓存策略。例如,对于缓存时间长的数据,设置较长的缓存有效期;对于实时性要求高的数据,设置较短的缓存有效期或不使用缓存。
  3. 使用Dio发送请求:通过Dio实例发送不同类型的网络请求,并根据缓存策略应用相应的缓存配置。

关键代码片段

  1. 添加依赖
dependencies:
  dio: ^4.0.0
  dio_cache_interceptor: ^4.0.0
  1. 初始化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),
  );
  1. 发送不同类型请求并应用缓存
// 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;
  }
}