Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Dart null checking idiom or best practice?

Tags:

dart

I have the following form of assignment & null checks to avoid double lookups in my maps.
Is there a better or more idiomatic way to do this in Dart?

bool isConnected(a, b){   List list;   return (     ((list = outgoing[a]) != null && list.contains(b)) ||     ((list = incoming[a]) != null && list.contains(b))   ); } 
like image 785
Mark Bolusmjak Avatar asked Jun 09 '13 05:06

Mark Bolusmjak


People also ask

How do you check for null in darts?

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 is the null safety in Dart?

When you opt into null safety, types in your code are non-nullable by default, meaning that variables can't contain null unless you say they can. With null safety, your runtime null-dereference errors turn into edit-time analysis errors.

How do you handle null safety in darts?

Use the null assertion operator ( ! ) to make Dart treat a nullable expression as non-nullable if you're certain it isn't null. is null, and it is safe to assign it to a non-nullable variable i.e.


1 Answers

As of Dart 1.12 null-aware operators are available for this type of situation:

bool isConnected(a, b) {   bool outConn = outgoing[a]?.contains(b) ?? false;   bool inConn = incoming[a]?.contains(b) ?? false;   return outConn || inConn; } 

The ?. operator short-circuits to null if the left-hand side is null, and the ?? operator returns the left-hand side if it is not null, and the right-hand side otherwise.

The statement

outgoing[a]?.contains(b) 

will thus either evaluate to null if outgoing[a] is null, or the boolean result of contains(b) if it is not.

That means the resulting statement will be one of the following:

bool outConn = null ?? false; // false bool outConn = false ?? false; // false bool outConn = true ?? false; // true 

The same applies to the inConn boolean, which means both inConn and outConn are guaranteed to be non-null, allowing us to return the result of ||ing the two.

like image 185
Pixel Elephant Avatar answered Sep 22 '22 23:09

Pixel Elephant