0

I'm trying to create an object class for the following api response.body

[
   {
      "medicationExt":null,
      "medicationSNOMED":{
         "codigo_snomed":"879978003",
         "nombre":"METOPROLOL COMPRIMIDOS 25mg",
         "descripcion":"producto que ...",
         "codigo_ingredient":"372826007",
         "descripcion_ingredient":"metoprolol (sustancia)",
         "presentacion":"comprimido",
         "volumen":25,
         "unidad":"mg"
      },
      "id_tratamiento":"tratamiento_cr2",
      "fecha_registro":"2023-03-15",
      "fecha_inicio":"2023-03-15",
      "fecha_termino":"",
      "estado":"activo",
      "frecuenciaDias":1,
      "instruccionesTexto":"Tomar 25 mg dos veces al día por vía oral. Tomar el medicamento a intervalos regulares durante el día, preferiblemente con las comidas. No dejar de tomar el medicamento de forma repentina sin consultar al médico.",
      "definedHours":true,
      "posologia":[
         {
            "hora_inicio":"08:00:00",
            "hora_fin":"09:00:00",
            "dosis":1,
            "unidad":"comprimido"
         },
         {
            "hora_inicio":"18:00:00",
            "hora_fin":"19:00:00",
            "dosis":1,
            "unidad":"comprimido"
         }
      ]
   },
   {...},
   {...},
]

And this is the object classes i have come up with.

class Welcome {
  final dynamic medicationExt;
  final MedicationSNOMED medicationSnomed;
  final String idTratamiento;
  final DateTime fechaRegistro;
  final DateTime fechaInicio;
  final String fechaTermino;
  final String estado;
  final int frecuenciaDias;
  final String instruccionesTexto;
  final bool definedHours;
  final List<Posologia> posologia;

  const Welcome({
    this.medicationExt,
    required this.medicationSnomed,
    required this.idTratamiento,
    required this.fechaRegistro,
    required this.fechaInicio,
    required this.fechaTermino,
    required this.estado,
    required this.frecuenciaDias,
    required this.instruccionesTexto,
    required this.definedHours,
    required this.posologia,
  });

  factory Welcome.fromJson(Map<String, dynamic> json) {
    return Welcome(
      medicationExt: json['medicationExt'],
      medicationSnomed: json['medicationSNOMED'],
      idTratamiento: json['id_tratamiento'],
      fechaRegistro: json['fecha_registro'],
      fechaInicio: json['fecha_inicio'],
      fechaTermino: json['fecha_termino'],
      estado: json['estado'],
      frecuenciaDias: json['frecuenciaDias'],
      instruccionesTexto: json['instruccionesTexto'],
      definedHours: json['definedHours'],
      posologia: <Posologia>[],
    );
  }
}

class MedicationSNOMED {
  String codigoSnomed;
  String nombre;
  String descripcion;
  String codigoIngredient;
  String descripcionIngredient;
  String presentacion;
  int volumen;
  String unidad;

  MedicationSNOMED({
    required this.codigoSnomed,
    required this.nombre,
    required this.descripcion,
    required this.codigoIngredient,
    required this.descripcionIngredient,
    required this.presentacion,
    required this.volumen,
    required this.unidad,
  });

  factory MedicationSNOMED.fromJson(Map<String, dynamic> json) {
    return MedicationSNOMED(
      codigoSnomed: json['codigo_snomed'],
      nombre: json['nombre'],
      descripcion: json['descripcion'],
      codigoIngredient: json['codigo_ingredient'],
      descripcionIngredient: json['descripcion_ingredient'],
      presentacion: json['presentacion'],
      volumen: json['volumen'],
      unidad: json['unidad'],
    );
  }
}

class Posologia {
  final String horaInicio;
  final String horaFin;
  final int dosis;
  final String unidad;

  const Posologia({
    required this.horaInicio,
    required this.horaFin,
    required this.dosis,
    required this.unidad,
  });

  factory Posologia.fromJson(Map<String, dynamic> json) {
    return Posologia(
      horaInicio: json['hora_inicio'],
      horaFin: json['hora_fin'],
      dosis: json['dosis'],
      unidad: json['unidad'],
    );
  }
}

My problem is mainly with the medicationSNOMED variable in the "Welcome" Class. How can i fill the variable without changing the "final" nor the "const" keywords on the classes?

I don't want to remove the "final" nor the "const" keywords because of performance (and because it looks cooler and prettier).

I have tryed something like this

  if (response.statusCode == 200) {
    List welcomesList = jsonDecode(response.body);

    List<Welcome> welcomes = [];
    for (int i = 0; i < welcomesList.length; i++) {
      Map<String, dynamic> welcomeMap = welcomesList[i];
      Map<String, dynamic> medicationSnomed = welcomeMap['medicationSNOMED'];
      welcomes[i].medicationSnomed = MedicationSNOMED.fromJson(medicationSnomed);

But i can't access the medicationSnomed variable in welcomes[i] because is a final varialbe.

Lemon
  • 1
  • 1
  • why dont you assign medicationSnomed: MedicationSNOMED.fromJson(json['medicationSNOMED']) in Welcome.fromJson(Map json). – Krish Bhanushali Jul 28 '23 at 04:06
  • As I usually do, I will create an extra class to receive the response. For example according to your sample, I will create class `WelcomesRepository`. This class will have a `List` property, and create `fromJson` for it to receive data. You try it! --- And should do as @KrishBhanushali said – Sơn Dương Jul 28 '23 at 04:10
  • Can u try nullable ```medicationSnomed``` as I mentioned in my answer – Moony-Stary Jul 28 '23 at 04:36
  • @KrishBhanushali response did the trick! – Lemon Jul 28 '23 at 16:17

1 Answers1

1

You remove const keyword, final keyword and make medicationSnomed field nullable try like this

  MedicationSNOMED? medicationSnomed;
  

  Welcome({
    this.medicationSnomed,
    required this.idTratamiento,
    required this.fechaRegistro,
    required this.fechaInicio,
    required this.fechaTermino,
    required this.estado,
    required this.frecuenciaDias,
    required this.instruccionesTexto,
    required this.definedHours,
    required this.posologia,
  });
Moony-Stary
  • 451
  • 10