Understanding how Dart helps prevent errors with null values
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.
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.
? after the type.// 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:
name cannot be null, so it must always hold a string value.middleName can be null, so you check if it's null before using it.
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.
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);
}
null carefully.? to allow variables to be null.late to delay initializing non-nullable variables.