CodeBlanks Logo Icon CodeBlanks

Sound null safety

Learn sound null safety and the type system.

Sound null safety

Sound null safety, introduced in Dart 2.12, is a type system feature that catches null reference errors at compile time. A type is non-nullable by default: int x cannot hold null.

To make it nullable, write int?. This lets the type system answer 'can this variable be null?'. null can only be assigned to nullable types; otherwise a compile-time error is raised.

Working with nullable values

To use a nullable value in a non-nullable context, a check is required. Three common ways: guarantee non-null with ! (maybeAge!), provide a default with ?? (maybeAge ?? 0) and check with if (maybeAge != null).

! is risky: it throws at runtime if the value is null. ?? is safe; it returns the default instead. Prefer ?? to keep code safe.

Practice Resolve a nullable age

Define a function int resolveAge(int? maybeAge) => maybeAge ?? 0; that takes a nullable int? and returns an int. In main add print(resolveAge(null)); and print(resolveAge(25));.

Starter code

main.dart
void main() {
  // define a resolveAge function
  // print calls with null and 25
}

Sample solution

main.dart
int resolveAge(int? maybeAge) => maybeAge ?? 0;

void main() {
  print(resolveAge(null));
  print(resolveAge(25));
}

Expected output

0
25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Nullable type declaration

Question
int? maybeAge = ____;
print(maybeAge);
Answer
int? maybeAge = null;
print(maybeAge);

Explanation: a nullable (int?) variable can be assigned null.

2 What does sound null safety provide?

  • Removes the garbage collector
  • Produces faster output
  • Catches null reference errors at compile time Correct answer
  • Makes all variables nullable

Explanation: sound null safety catches null errors at compile time.

3 Match the null safety operators

Term Meaning
int Non-nullable
int? Nullable
! Non-null assertion
?? Default value

All lessons in Expert