Dio的其他课程

时间:2019-11-25 09:03:46

标签: android-studio flutter dio

我正在为dio创建一个类 我与服务器的所有连接都发生在此类中 现在我想在其他类中调用onError和onSuccess 一个例子是在Java中通过接口完成的

谢谢

1 个答案:

答案 0 :(得分:0)

我已经做到了 首先,创建一个通用的dio类,

class NetworkRepository {
  Future<String> getRequest(String url) async {
    var dio = Dio();
    print(url.toString());
    dio.interceptors.add(InterceptorsWrapper(
        onRequest:(RequestOptions options) async {
          print("REQUEST[${options?.method}] => PATH: ${options?.path}");
          return options; //continue
        },
        onResponse:(Response response) async {
          print("RESPONSE[${response?.statusCode}] => PATH: ${response?.request?.path}");
          return response; // continue
        },
        onError: (DioError err) async {
         print("ERROR[${err.toString()}] => PATH: ${err?.request?.path}");
          return  err;//continue
        }
    ));
    Response response = await dio.get(url);
    print(response.toString());
    return response.toString();
  }
  dynamic requestInterceptor(RequestOptions options) async {
    return options;
  }

}

,并且您想在任何班级中调用它时,

 NetworkRepository().getRequest(projects).then((onValue) {
      var dataConvertedToJSON = json.decode(onValue);
      print(dataConvertedToJSON);
      setState(() {
        ProjectModel model = ProjectModel.fromJson(dataConvertedToJSON);
        mList.add(model);
      });
    });

您也可以尝试Bloc pattern这样做。