categoryModel.dart 1.91 KB
Newer Older
yenisleydi committed
1 2 3 4 5
// lib/src/models/category_model.dart

class CategoryModel {
  int id;
  int? version;
yenisleydi committed
6
  String? key;
yenisleydi committed
7 8
  String name;
  int createdDate;
yenisleydi committed
9 10 11
  CategoryModel? parentCategory;
  List<CategoryModel>? subCategories;
  bool? active;
yenisleydi committed
12 13 14 15

  CategoryModel({
    required this.id,
    this.version,
yenisleydi committed
16
    this.key,
yenisleydi committed
17 18
    required this.name,
    required this.createdDate,
yenisleydi committed
19 20 21
    this.parentCategory,
    this.subCategories,
    this.active,
yenisleydi committed
22 23 24
  });

  // Método para crear una instancia de CategoryModel desde un JSON
yenisleydi committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  factory CategoryModel.fromJson(Map<String, dynamic> json) {
    return CategoryModel(
      id: json['id'],
      version: json['version'],
      key: json['clave'],
      name: json['nombre'],
      createdDate: json['fechaCreado'],
      parentCategory: json['categoria'] != null
          ? CategoryModel.fromJson(json['categoria'])
          : null,
      subCategories: json['categorias'] != null
          ? CategoryModel.fromJsonArray(json['categorias'])
          : [],
      active: json['activo'],
    );
  }
yenisleydi committed
41

yenisleydi committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  // Este metodo sirve para para convertir una instancia de CategoryModel a JSON
  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "version": version,
      "clave": key,
      "nombre": name,
      "fechaCreado": createdDate,
      "categoria": parentCategory?.toJson(),
      "categorias": subCategories != null
          ? CategoryModel.toJsonArray(subCategories!)
          : [],
      "activo": active,
    };
  }
yenisleydi committed
57

yenisleydi committed
58 59 60 61 62 63 64
  // Método para crear una lista de CategoryModel desde un JSON
  static List<CategoryModel> fromJsonArray(json) {
    if (json == null) return [];
    var list = json as List;
    List<CategoryModel> listResult =
    list.map((data) => CategoryModel.fromJson(data)).toList();
    return listResult;
yenisleydi committed
65 66
  }

yenisleydi committed
67 68 69 70 71 72
  static toJsonArray(List<CategoryModel> list) {
    List<Map<String, dynamic>> listMap = [];
    for (CategoryModel item in list) {
      listMap.add(item.toJson());
    }
    return listMap;
yenisleydi committed
73 74
  }
}