Dart: List of generic class that implements fromJson function

527 views Asked by At

I have an api which returns an entity of type Category which has the following implementation:

class Category {
  final int id;
  final String title;

  Category({this.id, this.title});

  factory Category.fromJson(Map<String, dynamic> json) =>
      Category(id: json['id'], title: json['title']);
}

I am implementing fromJson function to map the result into an object of this class.


However, the result can contain some metadata and the actual result is incapsulated into a "content" field. The implementation would be something like this:

class CategoryWrapper {
  List<Category> content;
  int currentPage;
  int totalItems;
  int totalPages;

  CategoryWrapper({this.content, this.currentPage, this.totalItems, this.totalPages});

  factory CategoryWrapper.fromJson(Map<String, dynamic> json) {
    var list = json['content'] as List;
    List<Category> objectList = list.map((i) => Category.fromJson(i)).toList();

    return CategoryWrapper(content: objectList, currentPage: json['currentPage'], totalItems: json['totalItems'], totalPages: json['totalPages']);
  }
}

I am implementing the fromJson function here as well to map the results into an object of this class.


What I need is to have a generic class that can take any entity (for example Category) just like I can in Java. The class would look something similar to this:

class Wrapper<T> {
  List<T> content;
  int currentPage;
  int totalItems;
  int totalPages;

  Wrapper({this.content, this.currentPage, this.totalItems, this.totalPages});

  factory Wrapper.fromJson(Map<String, dynamic> json) {
    var list = json['content'] as List;
    List<T> objectList = list.map((i) => T.fromJson(i)).toList(); // this won't work

    return Wrapper(content: objectList, currentPage: json['currentPage'], totalItems: json['totalItems'], totalPages: json['totalPages']);
  }
}

But this won't work because I can't call the fromJson function from a generic type.


Is there a workaround for this I can use without complicating myself with two different classes for each entity?

0

There are 0 answers