Flutter Global Http Interceptor

后端 未结 1 1170
日久生厌
日久生厌 2021-01-20 13:39

I would like to know if it is possible to have a global HTTP interceptor to attach token in header for all requests in Flutter? I\'ve searched a lot and couldn\'t find any i

相关标签:
1条回答
  • 2021-01-20 13:53

    Using dio package u can do that :

    Dio dio = Dio(BaseOptions(
     connectTimeout: 30000,
     baseUrl: 'your api',
     responseType: ResponseType.json,
     contentType: ContentType.json.toString(),
    ))
    ..interceptors.addAll(
    [
      InterceptorsWrapper(onRequest: (RequestOptions requestOptions) {
        dio.interceptors.requestLock.lock();
        String token = ShareP.sharedPreferences.getString('token');
        if (token != null) {
          dio.options.headers[HttpHeaders.authorizationHeader] =
              'Bearer ' + token;
        }
        dio.interceptors.requestLock.unlock();
        return requestOptions;
      }),
      // other interceptor
     ],
    );
    
    0 讨论(0)
提交回复
热议问题