Search code examples
android-studioflutterdio

other class for Dio in flutter


i'm create a class for dio That all my connections to the server happen in this class Now I want to call onError and onSuccess in other class An example of this was done in Java with an interface

thanks


Solution

  • I have done like this, First, create a common 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;
      }
    
    }
    

    and when you want to call it in your any class,

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

    Also you can try Bloc pattern to do so.