如何防止Flutter Dio包接收器进入无限循环?

ctehm74n  于 2023-05-29  发布在  Flutter
关注(0)|答案(1)|浏览(337)

我想通过使用Flutter Dio包中的inceptors来刷新toki。
我使用onError方法使它再次请求,但即使我使用handler.reject(e),它也会进入无限循环。

class DioFetch {
  Dio dio = Dio();

  DioFetch() {
    demoInceptor();
  }

  demoInceptor() async {
    dio.interceptors.clear();
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          print("onRequest");
          return handler.next(options);
        },
        onError: (DioError e, handler) async {
          if (e.response != null) {
            if (e.response?.statusCode == 401) {
              print("statuscode: 401");
              final refresh = await refreshToken();
              if (refresh.statusCode == 200) {
                RequestOptions options = e.requestOptions;
                try {
                  var resp = await dio.request(e.requestOptions.path,
                      data: options.data,
                      cancelToken: options.cancelToken,
                      onReceiveProgress: options.onReceiveProgress,
                      onSendProgress: options.onSendProgress,
                      queryParameters: options.queryParameters);
                  return handler.resolve(resp);
                } on DioError catch (error) {
                  return handler.reject(error);
                }
              } else {
                return handler.reject(e);
              }
            }
          } else {
            return handler.next(e);
          }
        },
      ),
    );
  }

  Future<Response> refreshToken() async {
    //refresh token code. response dio
  }
}
hgtggwj0

hgtggwj01#

你可以用两种方法来解决
1-返回error而不是handler.reject(e);
2-不要使用相同的dio示例

  • 为令牌刷新创建另一个拦截器:
class TokenInterceptor extends Interceptor {

    TokenInterceptor()
        : dio = Dio(
      BaseOptions(
        baseUrl: EndPoints.baseUrl,
      ),
    )..interceptors.addAll([
      if (kDebugMode) PrettyDioLogger(),
    ]);

    final Dio dio;

    @override
    void onError(DioError err, ErrorInterceptorHandler handler) {
      // Do whatever you want
    }
  }
  • 将其添加到app dio客户端:
dio = Dio()
..interceptors.addAll([
  TokenInterceptor(),
]);

相关问题