其他 class for Dio in flutter

other class for Dio in flutter

我正在为 dio 创建一个 class 我与服务器的所有连接都发生在这个 class 现在我想在其他 class 中调用 onError 和 onSuccess 在 Java 中使用接口

完成了一个示例

感谢

我这样做过, 首先,创建一个普通的dio class,

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;
  }

}

当您想在任何 class、

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

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