Home > Software design >  How to handle 204 response in Retrofit using Dart?
How to handle 204 response in Retrofit using Dart?

Time:08-30

I'm using retrofit: ^3.0.1 1 and retrofit_generator: ^4.0.3 1 with Flutter and Dart.

I have a Retrofit method as such:

  @GET(ApiDashboard.urlFaults)
  Future<HttpResponse<List<FaultModel>>> fetchFaults({
    @Query(ApiDashboard.queryKey) required String key,
    @Query(ApiDashboard.queryFaultStartTime) required String startTime,
    @Query(ApiDashboard.queryFaultEndTime) required String endTime,
  });

This call returns an HTTP 204 No Content response, which causes a crash in Retrofit:

DioError [DioErrorType.other]: type 'String' is not a subtype of type 'List<dynamic>?' in type cast

CodePudding user response:

At the moment Retrofit doesn't support responses with 200 and 204 on the same call. The workaround is to use dynamic as the result and then deserialize it yourself like the following.

@GET(ApiDashboard.urlFaults)
Future<HttpResponse<dynamic>> fetchFaults({
  @Query(ApiDashboard.queryKey) required String key,
  @Query(ApiDashboard.queryFaultStartTime) required String startTime,
  @Query(ApiDashboard.queryFaultEndTime) required String endTime,
});

Usage is going to be something like:

final response = apiDashboard.fetchFaults(...);
if (response.statusCode == 204) return null;
return (response.data as List).map(item => FaultModel.fromJson(data));
  • Related