Screaming at the Silicon

Archive - Fedi

Dart Programming Notes: Null Safe Operators

Taking my lunch to dive into Flutter/Dart. I decided to learn this language a while ago and were I to re-evaluate the decision today, I might go elsewhere, but it seems cool, and the worse case scenario is that I'll end up being able to contribute to Veilid chat.

The most interesting thing I found today in Dart: Null aware operators. I haven't done heavy work in a language that has these (PHP 8 has these, but when I was working in PHP, the code was not on version 8).

?.

Example:

Assume you want to do a null check. Since I'm coming from a language without these operators, I'd do something like.

User user = new User.fromResponse(response);
if (user != null) {
   this.userAge = user.age 
}

Simpler method that exists in Dart

User user = new User.fromResponse(response);
this.userAge = user?.age; 

This line of code will simply assign userAge to null instead of throwing an error.

At first blush, I think this is more information dense than I like my code to be, but I'm thinking of how verbose Go can be and seeing the benefits here.

??

This operator is for assigning a default in the case of a null value

User user = new User.fromResponse(response);
this.userAge = user.age ?? 18; 

Pretty straightforward, the operator simply assigns a default value.

??=

This operator checks if a value is null, if it is, it assigns a value, if the value is not null, it returns the existing non-null value.

int x = 23;
x ??= 5; 

5 won't be assigned here because the value of x is already populated.

Reference

The book I'm working out of is Eric Windmill's Flutter In Action