Search code examples
flutterdartretrofit

How to access status code in a http call using Retrofit package?


retrofit takes a dio object so how can access that dio object to access the status code like 200 or something like this,

Retrofit base class

@RestApi(baseUrl: 'url')
abstract class ApiService {
  factory ApiService({Dio dio, String baseUrl}) {
    return _ApiService(dio, baseUrl: baseUrl);
  }

  @GET('/user')
  Future<List<Plant>> getUser(
    @Query('userId') String id,
  );
}

repositoy

class Repository {
  Dio dio = Dio();
  ApiService apiService;

  Repository() {
    dio = Dio();
    dio.interceptors.add(HeaderInterceptor());
    apiService = ApiService(
        dio: dio,
       baseUrl: 'http://10.0.2.2:8080/api',
        );
  }



  Future<User> getFloorPlanById(String id) async {
    try {
      final user = await apiService.getUser(id);
      return user;
    } on Exception catch (e) {
      print(e.toString());
      return null;
    }
  }
}

I want to access status code here so that I can show different types of screen based on status code.

If I directly use it then I have to call api again so that doesn't make sense.

so How can access status code here?


Solution

  • I found two ways to do this,

    Method-1

    use DioError

    on DioError catch (e) {
          print(e.toString());
    
        }
    

    here e contains the status code you can use it

    Method-2

    use HttpResponse

    make the return type HttpResponse of API call function

    ex-:

    Future<HttpResponse<Model>> getUser(
        @Query('userId') String id,
      );
    

    the result will contain the data along side the status code and message