Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-aware operator with Maps

Tags:

dart

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.

like image 553
creativecreatorormaybenot Avatar asked Jul 02 '18 17:07

creativecreatorormaybenot


People also ask

How do you know if a map is null in Dart?

In Dart, you can check if a given map is empty or not in several ways. The most convenient approaches are to use the isEmpty, isNotEmpty, or length properties.

What is a null-aware operator and how do we use it?

Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like.

What are null-aware operators in Dart?

Null-aware operators in Dart help resolve this issue. They're operators to say, "If this object or value is null , then forget about it: stop trying to execute this code." The number-one rule of writing Dart code is to be concise but not pithy.

Why is null safety important?

September 28, 2021. Null safety means that a variable cannot have a null or void value. This feature improves user satisfaction by reducing errors and app crashes. Null safety ensures that all runtime null-dereference problems are shown at compile-time.


1 Answers

This works:

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

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

like image 98
Günter Zöchbauer Avatar answered Sep 19 '22 15:09

Günter Zöchbauer