【问题标题】:Not Firing Interceptors in Flutter在 Flutter 中不触发拦截器
【发布时间】:2022-09-28 19:24:55
【问题描述】:

Flutter Custom Interceptors 代码在这里,它在 onRequest 方法以及 onResponse 方法和 onError 方法上显示错误。最近开始颤振实施。

 class AppInterceptors extends Interceptor {
      Dio _dio = Dio();
      SharedPreferences _prefs;
      TokenAnalyzer _tokenAnalyzer;
    
      AppInterceptors(this._dio, this._tokenAnalyzer);
      @override
      Future<dynamic> onRequest(RequestOptions options) async {
        _prefs = await _sharedPreferences;
        var accessToken = _prefs.get(\"access_token\") ?? \'\';
    
        return options;
      }
    
      @override
      Future<dynamic> onResponse(Response options) async {
        return options;
      }
    
      @override
      Future<dynamic> onError(DioError dioError) async {
       
    
        if (dioError.type == DioErrorType.response &&
                dioError.response.statusCode < 200 ||
            dioError.response.statusCode > 400) {
          if (dioError.response.statusCode == 500) {
            prefs.setString(\"ErrorMessage\", dioError.response.data);
            errorService.showErrorMessage(dioError.response.data);
            throw (dioError.response.data);
          } else if (dioError.response.statusCode == 401) {
            var _prefs = await _sharedPreferences;
            prefs.setString(\"ErrorMessage\", dioError.response.data);
         
          }
        }
        return null;
      }

这是另一个文件实现的DIO灌输

class DioHttpClient {
  Dio _dio = Dio();
  BaseOptions options = new BaseOptions(
      receiveTimeout: 1000 * 60,
      headers: {\'Content-Type\': \'application/json\', \'Authorization\': \'\'});

  DioHttpClient(TokenAnalyzer tokenAnalyzer) {
    _dio = new Dio(options);
    _dio.interceptors.add(AppInterceptors(_dio, tokenAnalyzer));
  }

  Dio get HttpClient {
    return _dio;
  }
}

API调用代码如下:

 Dio _httpClient1 = Dio();
 
  Future<T> post<T>(url, body, {allowAnnoymous = false}) async {
   
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      print(\"called new post method $url\");
      clientService.isBusy = true;
      String token = prefs.get(\"AccessToken\");
      Response response = await _httpClient1.post<T>(url,
          data: jsonEncode(body),
          options: Options(headers: {
            \"allowanonymous\": allowAnnoymous.toString(),
            \'Authorization\': \'Bearer $token\',
          }));
      print(\"====================   success post\");
      throwError(response);
      return response.data;
    } catch (ex) {
      throwErrorMessage();
      throw ex;
    }
  }

我得到以下错误,它显示错误像这样

\'AppInterceptors.onRequest\' (\'Future<dynamic> Function(RequestOptions)\') isn\'t a valid override of \'Interceptor.onRequest\' (\'void Function(RequestOptions, RequestInterceptorHandler)\').

你能帮帮我吗!谢谢提前!!!

    标签: flutter interceptor dio


    【解决方案1】:

    错误说明了一切:

    'AppInterceptors.onRequest' ('Future<dynamic> Function(RequestOptions)') isn't a valid override of 'Interceptor.onRequest' ('void Function(RequestOptions, RequestInterceptorHandler)').
    

    你有

    Future<dynamic> Function(RequestOptions)
    

    应该

    void Function(RequestOptions, RequestInterceptorHandler)
    

    example

    【讨论】:

    • 通过 RequestInterceptorHandler 处理程序后,错误消失了。但拦截器没有开火。你能帮我解释一下为什么它不开火吗?
    【解决方案2】:

    您在 onRequest 方法的参数中错过了 RequestInterceptorHandler 。

        override
              Future<dynamic> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
                _prefs = await _sharedPreferences;
                var accessToken = _prefs.get("access_token") ?? '';
            
                return
    
     options;
          }
    

    【讨论】:

    • 我通过了 RequestInterceptorHandler 处理程序,错误已修复。但拦截器仍然没有开火。
    • 你的拦截器也应该有类似的方法。就像,在请求“onRequest”方法 RequestInterceptorHandler 处理程序丢失。你更新了这个方法吗?
    • 是的。 Future<dynamic> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {}
    【解决方案3】:

    您必须更改所有三个被覆盖方法的声明(onError、onResponse 和 onRequest),如下所示:

    import 'package:dio/dio.dart';
    
    class Intercept extends Interceptor {
      
      @override              // add errorInterceptorHandler param 
      Future<dynamic> onError(DioError error, errorInterceptorHandler) async {
        // replace with your logic
        if (error.type == DioErrorType.connectTimeout ||
            error.type == DioErrorType.response) {
          print(error.response);
          print("CONNECTION TIMEOUT");
        }
        return error;
      }
    
      @override             // add responseInterceptorHandler param 
      Future<dynamic> onResponse(Response response, responseInterceptorHandler) async {
        // replace with your logic
        if (response.statusCode == 200) {
          print("RESPONSE--------->");
          print(response.data);
          print("<--------------------");
        }
        return response;
      }
    
      @override             // add requestInterceptorHandler param 
      Future<dynamic> onRequest(RequestOptions request, requestInterceptorHandler) async {
        // replace with your logic
        print("REQUESTING--------->");
        print(request.headers);
        print("<--------------------");
        return request;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      相关资源
      最近更新 更多