Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - Null-aware operator with Maps

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

What I would like to do

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:

list?.elementAt(index) ?? otherValue

What I am searching for

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?.valueFor(key) ?? otherValue

valueOf

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works:

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

Because the key will fallback to accessing an empty Map, which will always return null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...