Null-aware operator with Maps

Multi tool use
Multi tool use


Null-aware operator with Maps



I had the same problem with lists, now it is Map.


Map



The following syntax is not Dart, as in it does not compile:


map?[key] ?? otherValue



If my map was not a Map but a List, it would look like Günter pointed out here:


map


Map


List


list?.elementAt(index) ?? otherValue



I understand that map?[key] is not valid syntax and therefore I am searching for something like elementAt, which works for lists, for maps.


map?[key]


elementAt


map?.valueFor(key) ?? otherValue



That does obviously not yet exist. The problem has solutions and valueOf might be a good one as well.


valueOf




1 Answer
1



This works:


(map ?? const {})[key] ?? otherValue;



Because the key will access an emtpy Map, which will always return null.


key


Map


null





That does work and looks nice. I wonder how it did not come to my mind and if I should create an issue for that.
– creativecreatorormaybenot
Jul 2 at 17:42





You mean an issue for map?[key]. I think it's highly unlikely to be added. ? is only supported with .. Supporting it for list?[index] was requested but declined as far as I remember.
– Günter Zöchbauer
Jul 2 at 18:00


map?[key]


?


.


list?[index]





For something like map.valueOf(key).
– creativecreatorormaybenot
Jul 2 at 18:04


map.valueOf(key)





I see. Might be worth a try.
– Günter Zöchbauer
Jul 2 at 18:11





Consider using const {} to avoid creating a new map every time, at least when the types allow it.
– lrn
Jul 3 at 10:00


const {}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

kxzfrbgq3oNB 9guewC
AT9rb,Y

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications