Is there an elegant way to write the following statement for a map?
String? img = json['image'];
if (img != null) {
json['image'] = 'https://example.com/ingredients_100x100/' + img;
}
Basically I want to append the image IFF it exists and ignore if it does not. This has the opposite effect of ??= where the assignment occurs only if the image is found to be null. Which is similar to putIfAbsent.
The best I can come up with is this:
String? img = json['image'];
json['image'] = img != null ? 'https://example.com/ingredients_100x100/' + img : null;
I just feel like this is the wrong way of writing for null safety as the word null appears twice in a line.
You could also use the
update
method ofMap
. It will throw an error if the key 'image' does not exist. With theupdate
method, you can also easily provide a default if the keyimage
does not exist.