What is Null Safety in Dart?

2 Min Read

Null safety is a feature in Dart that ensures that variables can never be null (i.e., have no value) unless explicitly marked as such. This helps prevent NullPointerExceptions, which are a common source of bugs in many programming languages, including Dart.

With null safety, Dart distinguishes between two types of variables: those that can be null, and those that can’t. Variables that can be null are declared using the ? syntax after the type. For example:

String? name; // a variable that can be null

Variables that can’t be null are declared without the ? syntax:

String name; // a variable that can't be null

Dart also provides a way to access the value of a variable that can be null without risking a NullPointerException. This is done using the ?? operator, which returns the value of the variable if it’s not null, or a default value otherwise:

String name = someVariable ?? 'default name';

In this example, the value of someVariable is assigned to name if it’s not null. If someVariable is null, then name is assigned the value 'default name'.

Null safety is a powerful feature that makes it easier to write correct and reliable code, and it is one of the main features of Dart 2.12 and later.

Share this Article
Leave a comment