Dart Null Safety

Understanding how Dart helps prevent errors with null values

1. What is Null Safety? (Programming Definition)

Null Safety is a feature in Dart that helps prevent a common error called the null reference error. It means a variable that is expected to have a value cannot accidentally be null (which means “no value” or “empty”).

With null safety, Dart requires you to explicitly say if a variable can be null or not, helping catch errors before running the program.

2. Real-World Example of Null

Imagine a mailbox: if you expect a letter (value) inside it but the mailbox is empty (null), you can’t open or read anything. Null safety is like making sure the mailbox will always have a letter before you try to read it. If it can be empty, you have to check for that first.

3. Important Keywords & Concepts

4. Example: Variables with and without Null Safety

// Non-nullable variable: must always have a value
String name = "Alex";

// Nullable variable: can be null (notice the ?)
String? middleName;

// Using the variable safely
void main() {
  print("Name: $name");
  
  if (middleName != null) {
    print("Middle Name: $middleName");
  } else {
    print("Middle Name is not provided.");
  }
}

Explanation:

5. What Happens Without Null Safety?

Without null safety, your program might try to use a variable that has no value (null), which causes it to crash at runtime — called a null reference error.

6. Using late Keyword

Sometimes you want a variable that cannot be null but you don’t have the value immediately. You can use late to tell Dart: "I promise I will set this value later."

late String description;

void main() {
  description = "This is a Dart example.";
  print(description);
}

7. Summary