CategoriaModel.dart 1.91 KB
Newer Older
nayeli92433 committed
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 CategoriaModel {
  int id;
  int? version;
  String? key;
  String? name;
  int? createdDate;
  CategoriaModel? parentCategory;
  List<CategoriaModel>? subCategories;
  bool? active;

  CategoriaModel({
    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 CategoriaModel.fromJson(Map<String, dynamic> json) {
    return CategoriaModel(
      id: json['id'],
      version: json['version'],
      key: json['clave'],
      name: json['nombre'],
      createdDate: json['fechaCreado'],
      parentCategory: json['categoria'] != null
          ? CategoriaModel.fromJson(json['categoria'])
          : null,
      subCategories: json['categorias'] != null
          ? CategoriaModel.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
          ? CategoriaModel.toJsonArray(subCategories!)
          : [],
      "activo": active,
    };
  }

  // Método para crear una lista de CategoryModel desde un JSON
  static List<CategoriaModel> fromJsonArray(json) {
    if (json == null) return [];
    var list = json as List;
    List<CategoriaModel> listResult =
    list.map((data) => CategoriaModel.fromJson(data)).toList();
    return listResult;
  }

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