category_model.dart 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
// lib/src/models/category_model.dart

class CategoryModel {
  int id;
  int? version;
  String? key;
  String? name;
  int? createdDate;
  CategoryModel? parentCategory;
  List<CategoryModel>? subCategories;
  bool? active;

  CategoryModel({
    required this.id,
    this.version,
    this.key,
    this.name,
    this.createdDate,
    this.parentCategory,
    this.subCategories,
    this.active,
  });

  // Método para crear una instancia de CategoryModel desde un JSON
  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'],
    );
  }

  // 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,
    };
  }

  // 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;
  }

  static toJsonArray(List<CategoryModel> list) {
    List<Map<String, dynamic>> listMap = [];
    for (CategoryModel item in list) {
      listMap.add(item.toJson());
    }
    return listMap;
  }
}