Home > other >  How do I resolve a map value called on null
How do I resolve a map value called on null

Time:03-10

I have a contact model that uses maps but the return is null thus causing aysnc suspension. I have tried tried setting these maps to return an empty list but to no avail do I manage to resolve the issue.

   ContactModel{
    //factory method constructor 
    emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))),
    tasks:  List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))),
    notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))),

     }

The error returns as : No such method map called on null. Receiver null

I have tried to resolve the issue by writing it as such

ContactModel{
    //factory method constructor 
    emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() ?? [],
    tasks:  List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() ?? [],
    notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() ?? [],

     }

CodePudding user response:

You can try null checking the json like so :

ContactModel{
    emails: parsedJson['Emails'] != null ? List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() : [],
    tasks: parsedJson['Tasks'] != null ?  List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() : [],
    notes:parsedJson['Notes'] != null ?  List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() : [],
}

CodePudding user response:

Basically, I always check 2 things when working with JSON types :

  • You must check your JSON contains the key you're looking for
  • You must check null value being returned if the key exist.

I recommend you doing this double check like this :

if(parsedJson.isNotEmpty) {
  List<dynamic> emails = [];
  if (parsedJson.containsKey('Email') && parsedJson['Email'] is List) {
    emails = List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x)))
  }
  ContactModel({emails: emails});
}

This way, you always make sure you've got the right type, and avoid production error (imagine your API going nuts). It's more verbose, I know, but to me, good code requires accuracy

  • Related