dio icon indicating copy to clipboard operation
dio copied to clipboard

自定义了一个Restful的类 但是使用的时候会报DioError [DioErrorType.DEFAULT]: Concurrent modification during iteration: Instance of 'Interceptors'.#0

Open hl9565 opened this issue 7 years ago • 3 comments

class HttpRestful { // 全局的dio实例 static Dio dio;

// api地址和超时时间 static const String API_PREFIX = serviceUrl; static const int CONNECT_TIMEOUT = 10000; static const int RECEIVE_TIMEOUT = 3000;

// request method static Future request(String url, {Map<String, dynamic> data, String method}) async { data = data ?? {}; method = method ?? 'list';

// 打印请求相关信息:请求地址、请求方式、请求参数
print('请求地址:【' + method + '  ' + url + '】');
print('请求参数:' + data.toString());

Dio dio =  createInstance();
String token;
token = await getToken();
LogicError err = LogicError();
dio.interceptors
    .add(InterceptorsWrapper(onRequest: (RequestOptions options) async{
  if (token != null) {
    // 如果本地存在token
    // 在请求被发送之前设置token

// print('token$token'); dio.lock(); options.headers["Authorization"] = 'Bearer ' + token; dio.unlock(); } return options; //continue }, onResponse: (Response response) { // 在返回响应数据之前做一些预处理 print('响应数据:' + response.toString()); return response; // continue }, onError: (DioError e) { // 当请求失败时做一些预处理 print('请求出错:${e}'); return e; })); }

//dio拦截器设置token static getToken() async { String token; SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化 token = prefs.getString('token'); //获取当前token //判断token是否为空,为空说明是第一次添加,或者被key被清除了。 return token; }

// 创建 dio 实例对象 static Dio createInstance() { if (dio == null) { // 全局属性:请求前缀、连接超时时间、响应超时时间 BaseOptions options = new BaseOptions( baseUrl: API_PREFIX, connectTimeout: CONNECT_TIMEOUT, receiveTimeout: RECEIVE_TIMEOUT, ); dio = new Dio(options); } return dio; }

hl9565 avatar Jun 05 '19 09:06 hl9565

same problem

right7ctrl avatar Jun 10 '19 07:06 right7ctrl

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, please make sure it is up to date and if so, add a comment that this is still an issue to keep it open. Thank you for your contributions.

stale[bot] avatar Jul 10 '19 07:07 stale[bot]

Just use a singleton for your Dio client

class Service {
  Service._privateConstructor();
  static final Service instance = Service._privateConstructor();

  Dio dio;
  bool isRetryCall = false;

  Future<Dio> client() async {
    if (dio == null)
      dio = Dio(); // with default Options
    else
      return dio;
interceptor etc

amorenew avatar Aug 05 '19 13:08 amorenew