Using the Chopper Library

https://www.raywenderlich.com/books/flutter-apprentice/v1.0.ea2/chapters/13-using-the-chopper-library

This chapter is dedicated to obtaining Responses from an api using libraries Chopper and JsonConverter.

The code in Github is here

He also proposes the use of a response wrapper like functional programming, of the type Success/Error.

The ModelConverter from Response to Success/Error wrapper, applies to the APIRecipeQuery Model and only uses one method in this line final recipeQuery = APIRecipeQuery.fromJson(mapData);.

It seems quite logical to make a generic ModelConverter, since it is a very useful class.

So, I have tried by passing the model in the constructor as a parameter:

class ModelConverter <T extends JsonConverter> implements Converter {
  final T model;
  ModelConverter ({@required this.model});
  . . .

and I invoke it in recipe_service.dart with converter: ModelConverter(model: APIRecipeQuery), but I don’t know how to reference the model statically before it’s created, and can’t access the method model.fromJson

Next, I have tried passing just the function converter:

class ModelConverter implements Converter {
  Function fromJson;
  ModelConverter ({@ required this.fromJson});
  . . .

with a getter in the API, and in recipe_service.dart with converter: ModelConverter(fromJson: APIRecipeQuery.fjConverter)

class APIRecipeQuery {
  static Function get fjConverter => _ $ APIRecipeQueryFromJson;
 . . .

But I can’t get it to work.

What would be the best approach to make the ModelConverter generic?
Thanks in advance.

I’ve found a solution inspired by this post

model_converter.dart

. . .
typedef CreateModelFromJson = dynamic Function(Map<String, dynamic> json);

class ModelConverter<Model> implements Converter {
  final CreateModelFromJson fromJson;

  ModelConverter({@required this.fromJson});
. . .
  final query = fromJson(mapData) as Model;
. . .

and recipe_service.dart

. . .
      converter: ModelConverter<APIRecipeQuery>(
        fromJson: (json) => APIRecipeQuery.fromJson(json),
      ),
. . .

:wink: