Sitemap
Arte Bi

Arte Bi

Dart: null safety

2 min readAug 17, 2023

This article is part of a series on How to start creating mobile applications for Android or iOS using Dart & Flutter.

Press enter or click to view image in full size
Photo by Oskar Yildiz on Unsplash

null

In the Dart programming language, the null value is used to indicate the absence of a value or the absence of a reference to any object. This allows you to explicitly indicate that a variable does not hold any valid value.

Null safety

“Null safety” is a feature in the Dart language that helps prevent many errors related to null values, thereby enhancing program reliability and safety.

In the Dart language prior to the introduction of “Null safety,” variables could hold a null value (indicating the absence of a value), which could lead to unpredictable errors during program execution. For example:

String name;
print(name.length); // Error! Attempt to access a property of a null value.

With “Null safety,” new data types and annotations have been introduced, which allow you to specify whether a variable can accept a null value or not. Here’s how it works:

Nullable variables

Get Arte Bi’s stories in your inbox

Join Medium for free to get updates from this writer.

Variables that can have a null value are marked with a question mark ? after the data type. For example:

String? name;

Now the variable “name” can hold a string or null.

Non-nullable variables

Variables that cannot have a null value are declared without a question mark. For example:

String firstName = 'John';

In this case, the variable “firstName” cannot contain a null value.

Safe access operators

To work safely with nullable variables, the operators ?. and ?? are introduced. The ?. operator allows you to invoke methods and access properties only if the variable is not equal to null. The ?? operator allows you to specify a default value that will be used if the variable is null. Example:

String? name;
int nameLength = name?.length ?? 0; // If "name" is not null, its length will be returned; otherwise, 0 will be returned.

All of the above allows avoiding errors related to null values and simplifies working with variables that can be null.

--

--