Home > Back-end >  How to update Model with the correct value type
How to update Model with the correct value type

Time:12-14

I have this code that fetch data from internet:

Future fetchCfo(String barCode, String url) async {
  final response = await http.get(Uri.parse(url   barCode));
  if (response.statusCode == 200) {
    Map<String, dynamic> responseBody = json.decode(utf8.decode(response.bodyBytes));
    responseBody.forEach((key, value) {
      if (value == null) {
        responseBody.update(key, (value) => "");
      }
    });
    return CfoModel.fromJson(responseBody);
  } else {
    return null;
  }
}

And I need to replace the null values ​​according to their type, for example if a field that was supposed to be an integer returns a null I need to replace it with 0, if a field that was supposed to be a list returns a null I need to replace it with a list empty []; and I don't know how to do this, my code replaces Strings but if a null appears in an int field, the code breaks.

For example, my model:

 String? interfaceStatus;
    bool? trasnP;
    int? id;
    String? name;
    String? date;
    bool? requiredStatus;
    int? numberOf;
    int? numberRegion;
    List? parameters;

In case numberRegion returns a null, I need to replace with 0; In case Transp returns a null, I need to replace with false; in case name returns a null, I need to replace with empty String "";

Response I'm getting:

{
   "interfaceStatus":"ok",
   "trasnP":false,
   "id":null,
   "name":null,
   "date":null,
   "requiredStatus":true,
   "numberOf":23,
   "numberRegion":27,
   "parameters":null
}

What I want to return:

{
   "interfaceStatus":"ok",
   "trasnP":false,
   "id":0,
   "name":"",
   "date":"",
   "requiredStatus":true,
   "numberOf":23,
   "numberRegion":27,
   "Parameters":[
      
   ]
}

Anyone has a solution for this ?

CodePudding user response:

I would recommend not updating any values in the responseBody just leave them as null but in the fromJson function you can give default values with the ?? operator such as:

  fromJson(Map response) {

    return CfoModel(
      id: response[id] ?? 0,
      array: response[array_element] ?? [],
  );
}
  • Related