What is Null Safety?
Null safety is a type system feature (introduced in Dart 2.12) that eliminates null reference errors — one of the most common and frustrating bugs in programming. With null safety, the compiler guarantees that a variable cannot be null unless you explicitly allow it.
Why Does It Matter?
In languages without null safety, any variable can be null at any time, causing NullPointerException errors at runtime. Dart's null safety catches these errors at compile time — before your code even runs.
// Without null safety (old Dart / other languages):
String name = null; // allowed — crashes at runtime
print(name.length); // NullPointerException!
// With null safety (Dart 2.12+):
String name = null; // COMPILE ERROR — String cannot be null
String? name = null; // OK — String? allows null
Non-Nullable by Default
In Dart with null safety, all types are non-nullable by default. The compiler guarantees they always hold a valid value:
int age = 25; // cannot be null
String name = 'Bob'; // cannot be null
bool flag = true; // cannot be null
// age = null; ← COMPILE ERROR
Making Variables Nullable
Add ? after the type to allow null values:
int? age = null; // allowed
String? name = null; // allowed
double? score; // defaults to null
// Must check before use:
if (age != null) {
print(age + 1); // safe
}
print(age?.toString()); // null-aware access
Null Safety Operators
| Operator | Name | Use |
? | Nullable type | String? name |
?? | If-null (default) | name ?? 'Guest' |
??= | Null-aware assign | name ??= 'Guest' |
?. | Null-aware access | name?.length |
! | Null assertion | name! |
late | Late initialization | late String name |
Example
void main() {
String firstName = 'John'; // non-nullable
String? lastName = null; // nullable
// Use ?? for a default
print('$firstName $${lastName ?? 'Doe'}'); // John Doe
// Null-aware access
print(lastName?.toUpperCase()); // null
// Assign lastName
lastName = 'Smith';
print(lastName.toUpperCase()); // SMITH (safe — no longer null)
}
Output:John Doe
null
SMITH
🧠 Quiz
1. In Dart null safety, can a String variable be null by default?
- A) Yes
- B) No ✅
- C) Only if declared with var
- D) Only at class level
2. What does adding ? after a type mean?
- A) The variable is optional
- B) The variable can be null ✅
- C) The variable is checked at runtime
- D) The variable is private
Summary
Dart null safety (since 2.12) makes all types non-nullable by default. Add ? to allow null. The compiler catches null errors at compile time, not runtime. Key operators: ??, ??=, ?., !, and late — each handles nullable values safely.