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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With