Search code examples
flutterflutter-http

Common method for flutter api calls


Is there any example that I can refer to about Common class/method for flutter API calls(GET,POST,...) in flutter? I have handled all the API requests in a common method in react native, I'm not sure how to implement it in flutter.


Solution

  • you have to call getRequest using url parameter

    Future<Response> getRequest(String url) async {
        Response response;
        try {
          response = await _dio.get(url,
              options: Options(headers: {
                HttpHeaders.authorizationHeader:
                    'Bearer $accessToken'
              }));
          print('response $response');
        } on DioError catch (e) {
          print(e.message);
          throw Exception(e.message);
        }
        return response;
      }
    

    here is the post method

    Future<Response> posRequestImage(String url, data) async {
    
        try {
          response = await _dio.post(
            url,
            data: formData,
            options: Options(headers: {
              HttpHeaders.authorizationHeader:
                  'Bearer $accessToken'
            }),
          );
          if (response.statusCode == 200) {
            return response;
          }
          print('post response $response');
        } on DioError catch (e) {
          print(e.message);
          throw Exception(e.response?.statusMessage);
        }
        return response;
      }