Sub topic 1
Why Null Safety Exists
Prerequisites
You should know basic Dart syntax, including variables, functions, and classes. You should also be able to run a Dart file with dart run or DartPad.
The Problem With Null
Null is a value that means "no value." Before null safety, any variable could hold null. Code such as name.length compiled even when name was null, then crashed at runtime with a null reference error. Testing often missed these crashes because they appeared only on specific code paths.
Null safety moves this check to compile time. The compiler rejects code that could fail this way, so you find the error before the program runs.
Non-Nullable by Default: T Versus T?
In Dart 3, a type such as String cannot hold null. A type with a question mark, such as String?, can hold either a string or null.
void main() {
String name = 'Ada';
String? nickname;
// name = null; // Compile-time error: null is not a String
nickname = 'Ace';
print(nickname ?? 'none'); // Ace
}Use T when a value must always exist. Use T? only when a missing value is a normal, expected state.
What "Sound" Means
Dart's null safety is sound. If an expression has a non-nullable type, it can never evaluate to null at runtime. The compiler checks this across the whole program, so you do not need defensive checks on every value.
The guarantee holds unless you opt out with the ! operator or use legacy code that has not been migrated.
Handling Null With ?., ??, ??= and ?[]
?.calls a member only when the value is not null. Otherwise, the whole expression is null.??returns the left value, or the right value when the left is null.??=assigns the right value only when the left variable is null.?[]reads an index only when the list is not null.
void main() {
String? city;
print(city?.length); // null
print(city ?? 'unknown'); // unknown
List<int>? scores;
print(scores?[0]); // null
city ??= 'Paris';
print(city); // Paris
}Exercise
What does print(scores?[0] ?? -1); print when scores is null?
Show answer
It prints -1. The ?[] returns null because scores is null, and ?? replaces that null with -1.