Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking nested Dart Map for nulls

Tags:

dart

I have a dart Map I'm converting from json that itself contains nested maps. Unfortunately, because this data comes from a web service I don't control, sometimes some of the nested values are in fact null.

For instance, if I have a value defined as follows:

data = json.decode(response.body) as Map;
  if (data["media_details"]["sizes"]["thumbnail"]["source_url"]

..sometimes the ["thumbnail"] value will in fact be null.

Is there a concise way to check for null in these situations besides tediously walking down the Map and checking:

if (data["media_details"] != null) {
 if(data["media_details["sizes"] != null) {

//etc

I'm not sure if dart's null-aware operators are of use in situations like this, but am interested to learn if they are.

like image 850
larryq Avatar asked Jun 03 '19 05:06

larryq


2 Answers

There is currently no concise way to avoid repeated null checks for [] lookups. We hope to add that to the Dart language in a later version.

The best I can propose is:

 dynamic tmp;
 data = ((tmp = json["media_details"]) == null ? null 
        : (tmp = tmp["sizes"]) == null ? null
        : (tmp = tmp["thumbnail"]) == null ? null
        : tmp["source_url"];

That's ... still very ugly.

If you don't mind a little overhead, you can create a helper class:

class IndexWalker {
  dynamic value;
  IndexWalker(this.value);
  IndexWalker operator[](Object index) {
    if (value != null) value = value[index];
    return this;
  }
}

then you can do:

data = IndexWalker(json)["media_details"]["sizes"]["thumbnail"]["sources_url"].value;

Looks better, and a good optimizing compiler should be able to avoid the allocation.

like image 126
lrn Avatar answered Nov 04 '22 23:11

lrn


You can use deep_pick package: https://pub.dev/packages/deep_pick

data = json.decode(response.body) as Map;
  if (pick(data, "media_details", "sizes", "thumbnail", "source_url")
like image 2
Mutlu Simsek Avatar answered Nov 04 '22 23:11

Mutlu Simsek