使用http响应标头的Flutter Cache JSON响应 [英] Flutter Cache JSON response using http response header

查看:79
本文介绍了使用http响应标头的Flutter Cache JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为服务器JSON响应创建并使用缓存.

类似于截击响应缓存. https://stackoverflow.com/a/32022946/1993001 Android

我正在使用DIO进行网络操作.

解决方案

您可以在Dio请求的顶部使用拦截器创建自己的缓存.

您可以自己创建:

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;
  }
}

,然后将其用于:

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

或仅检查库: https://pub.dev/packages/dio_cache

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.

解决方案

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

这篇关于使用http响应标头的Flutter Cache JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆