Null Safety in Dart

Null Safety in Dart#

In this section, you will learn about null safety in the Dart programming language. Null safety helps prevent null reference errors by enforcing strict checks at compile time. This section covers the following topics:

  1. Null Safety in Dart
  2. Type Promotion in Dart
  3. Late Keyword in Dart
  4. Null Safety Exercise
  5. Nullable Types and Default Values
  6. Null Safety with Collections

Null Safety in Dart#

  • Definition: Null safety ensures that variables cannot be null unless explicitly declared as nullable.
  • Purpose: To eliminate runtime null dereference errors and enhance code reliability.
  • Syntax: Use ? to indicate that a variable or parameter can be null, and ! to assert that a value is non-null.

Example:

void main() {
  int? maybeNumber; // Nullable integer
  maybeNumber = 10;

  // Accessing value safely
  if (maybeNumber != null) {
    print(maybeNumber + 5); // Outputs: 15
  }
}
On this page: