Sound null safety
Learning objectives
- You know about null safety in Dart.
Disallowing null as a value
Dart is a null safe language, which means that variables cannot contain the value null
unless explicitly allowed. As an example, attempting to create a task as follows would lead to an error.
The error for the above program is The argument type 'Null' can't be assigned to the parameter type 'String'. The same error persists even if we try to create a separate String variable (with the value null
) and pass it to the constructor of the class Task.
void main() {
String s = null;
final t = Task(s, true);
}
Dart compiler looks for potential occurrances of the null value and seeks to prohibit its use.
Similarly, even if we attempt to create the Task based of a function that must return a String but returns the null value, we also see an error.
void main() {
final t = Task(trickName(), true);
}
String trickName() {
return null;
}
Now, the error indicates that A value of type 'Null' can't be returned from the function 'trickName' because it has a return type of 'String'.
In effect, the Dart compiler looks for potential occurrances of the null value and seeks to prohibit its use. Null-safety in Dart is also the key reason why we need to either provide a default value for a named argument or set the named argument as required.
Allowing null as a value
It is, however, possible to allow null
as a value for an instance property. In such a case, the variable type will be annotated with a question mark as follows. The following example allows a situation where the name of the task can be null.
Note that variable types that allow null values differ from their non-nullable counterparts. For example, contents of a String?
cannot be assigned to String
as the following example demonstrates.
If we believe that the potentially nullable value is not null, we can claim so using an exclamation mark during assignment. In the following example, we claim that the name of the task is not null and assign it to the variable taskName
.
In the above example, the compiler no longer produces an error. However, when we run the program, we see an error message "Uncaught TypeError".
Avoid nullable objects
Although it is beneficial to know about nullable objects (some Flutter libraries e.g. use them), when writing code, it is beneficial to avoid using them. This provides the full benefits of the Dart compiler as a support tool for debugging programs.