Converting JSON response to Model Object using Chopper library in flutter?

616 views Asked by At

I am using the Chopper library to invoke rest API calls.

I have followed Raywenderlich Chopper Tutorial tutorial to implement API calls in my project.

In this tutorial, they have used the below code to convert JSON response to Popular model object.

    try {
      var mapData = json.decode(body);
      **var popular = Popular.fromJson(mapData);**
      return response.copyWith<BodyType>(body: popular as BodyType);
    } catch (e) {
      chopperLogger.warning(e);
      return response.copyWith<BodyType>(body: body);
    }

This is fine. But in my project, I have to make multiple API calls and need to decode multiple JSON responses to Dart model objects.

So how to decode multiple API calls responses? Do I need to do something like below:

      if(mapData['popularResponse'] != null) {
        Popular popularResponse = Popular.fromJson(mapData);
        return response.copyWith<BodyType>(
                  body: popularResponse as BodyType);
      } else if(mapData['articleResponse'] != null) {
        Article articleResponse = Article.fromJson(mapData);
        return response.copyWith<BodyType>(
                  body: articleResponse as BodyType);

      } else if(......) {
        ......
      }

How to proceed further?

1

There are 1 answers

0
Bismeet singh On

One request per api file, that is the only way I see this possible, I think the http package is good enough and chopper is more trouble than its worth.