Flutter: Sublist model of the same model, (Class tree)

Asked

Viewed 68 times

0

I am creating an application where I call an external API that returns a list of categories, each category can have a list of categories (subcategories). I don’t know how I can make my model right.

Right now I have following Model:

  class Category {
  String id;
  String name;
  String description;
  String slug;
  String image;
  int parent;
  int count;
  List<Category> childs;

  Category(
      {this.id,
      this.name,
      this.description,
      this.slug,
      this.image,
      this.parent,
      this.count,
      this.childs});

  factory Category.fromJson(jsonData) {
    return Category(
      id: jsonData['id'].toString(),
      name: jsonData['name'],
      description: jsonData['description'],
      slug: jsonData['slug'],
      image: jsonData['image'],
      parent: jsonData['parent'],
      count: jsonData['count'],
      childs: jsonData['childs'],
    );
  }

  toJson() {
    return jsonEncode({
      'id': id,
      'name': name,
      'description': description,
      'slug': slug,
      'image': image,
      'parent': parent,
      'count': count,
    });
  }

and make the GET request in my category_repository which is called in my store (Mobx).

STORE:

@action
  Future<void> getCategoriesTree() async {
    setLoading(true);
    clear();
    final response = await repository.getCategoriesTree();
    response.map((category) {
      addToCategoriesTree(Category.fromJson(category));
    }).toList();
    categoriesTree = categoriesTree;
    setLoading(false);
  }

Repository:

try {
      final response = await _woocommerce.get("get-tree-categories");          
      return response;
    } on DioError catch (e) {
      print('CATCH DO GETCATEGORIES - CATEGORIES REPOSITORY');
      print(e.toString());
      print(e.response.request.baseUrl);
      print(e.response.request.path);
      print(e.response.headers);
      print(e.response.statusCode);
      print(e.response.data);
    }

In the store I do the return mapping and the categories are added in the observable list "categoriesTree", but the subcategories that are returned in each category do not end as a Category object, as I make the "sub list" also each as Category Object?

The same is true for each subcategory that may have a list of subcategories. there are 3 categories levels.

1 answer

2


You need to treat these same sub-categories made with the categories.

I’ll leave you an example and you apply for your case, let’s assume that the API returns you a list of users and each user can have N emails.

JSON returned by API:

      {
         "id":"001",
         "nome":"Matheus Ribeiro",
         "telefone":"5514981234567",
         "emails":[
            {
               "email":"[email protected]",
               "tipo":"contato"
            },
            {
               "email":"[email protected]",
               "tipo":"financeiro"
            }
         ]
      },

So come on...

Create a class to store the data of each email:

class Email {
  Email({this.email, this.tipo});

  final String email;
  final String tipo;
}

Creates a class to store each user’s data along with their N emails

class Usuario {
  Usuario({this.id, this.nome, this.telefone, this.emails});
 
  final String id;
  final String nome;
  final String telefone;
  final List<Email> emails;
  
  factory Usuario.fromJson(Map<String, dynamic> json) => Usuario(
    id: json["id"],
    nome: json["nome"],
    telefone: json["telefone"],
    emails: (json["emails"] as List).map((conteudo) => Email.fromJson(conteudo)).toList());
}

It is at this point that "magic occurs"

emails: (json["emails"] as List).map((conteudo) => Email.fromJson(conteudo)).toList());

In my returned JSON, you understand that emails come in a list, so I take the value of the object as List and make a map to run each item and go adding to the list from within the class Usuario.

You can see the full article I did here on this link: Decomposing JSON into Flutter

  • 1

    That’s right :) thanks for the availability

Browser other questions tagged

You are not signed in. Login or sign up in order to post.