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.
That’s right :) thanks for the availability
– Laranja Mecânica