Flutter Cache JSON response using http response header

陌路散爱 提交于 2021-02-20 11:44:45

问题


I'm trying to create and use a cache for a server JSON response.

something like volley response caching does. https://stackoverflow.com/a/32022946/1993001 in Android

I am using DIO for network operations.


回答1:


You can you create your own cache with Interceptors on top of Dio requests.

You can create in on your own:

import 'package:dio/dio.dart';

class CacheInterceptor extends Interceptor {
  CacheInterceptor();

  var _cache = new Map<Uri, Response>();

  @override
  onRequest(RequestOptions options) async {
    return options;
  }

  @override
  onResponse(Response response) async {
    _cache[response.request.uri] = response;
  }

  @override
  onError(DioError e) async{
    print('onError: $e');
    if (e.type == DioErrorType.CONNECT_TIMEOUT || e.type == DioErrorType.DEFAULT) {
      var cachedResponse = _cache[e.request.uri];
      if (cachedResponse != null) {
        return cachedResponse;
      }
    }
    return e;
  }
}

and then use it with:

final dio = Dio()..interceptors.add(CacheInterceptor());   

or just check the library: https://pub.dev/packages/dio_cache



来源:https://stackoverflow.com/questions/59115399/flutter-cache-json-response-using-http-response-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!