Welcome to OStack Knowledge Sharing 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...