skip to Main Content

I have two json files that I retrieved via an api. I want to create a relationship between the product and the category for display in my product listview the name of the category instead of the id of the category.

here i have an example of my first json file which contains all the products.

listing.json

[
   {
      "id":1461267313,
      "category_id":4,
      "title":"Statue homme",
      "description":"...",
      "price":140.00,
      "images_url":{
         "small":"...",
         "thumb":"..."
      },
      "creation_date":"2019-11-05T15:56:59+0000",
      "is_urgent":false
   },
   {
      "id":1691247255,
      "category_id":8,
      "title":"Pc portable hp elitebook 820 g1 core i5 4 go ram 250 go hdd",
      "description":"...",
      "price":199.00,
      "images_url":{
         "small":"...",
         "thumb":"..."
      },
      "creation_date":"2019-10-16T17:10:20+0000",
      "is_urgent":false
   },
]

and there the second json file which contains the categories

categories.json

[
  {
    "id": 1,
    "name": "VĂ©hicule"
  },

  //from 1 to 11

  {
    "id": 11,
    "name": "Enfants"
  }
]

I created a product model and a category model

product.dart

class Product {
  int? id;
  int? categoryId;
  String? title;
  String? description;
  double? price;
  ImagesUrl? imagesUrl;
  String? creationDate;
  bool? isUrgent;

  Product(
      {this.id,
      this.categoryId,
      this.title,
      this.description,
      this.price,
      this.imagesUrl,
      this.creationDate,
      this.isUrgent});
}

category.dart

class Category {
  int? id;
  String? name;

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

2

Answers


  1. Chosen as BEST ANSWER

    Finally, I created a map to match the category id of my product to the name field of my class category. I get it back with the key like that. productByCat return type is Map<int, String>.

    for (int i = 0; i < dataProduct!.length; i++) {
         for (int y = 0; y < dataCategory!.length; y++) {
               if (dataProduct?[i]['category_id'] == dataCategory?[y]['id']) {
                  productByCat[dataProduct?[i]['category_id']] = dataCategory?[y]['name'];
               }
         }
    }
    return productByCat;
    

  2. create a new class ProductItem. After converting json file add both product & category in an order to the new class.
    class ProductItem { final Product product; final Category category; ProductItem({required this.product, required this.category}); }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search