Dart Null Safety
null means "no value". In many languages any variable can secretly be null, and forgetting to check leads to the infamous null pointer exception. Dart has sound null safety: a variable can only hold null if its type says so, and the compiler forces you to handle that case.
Nullable and non-nullable types
Types are non-nullable by default. Add a ? to allow null.
void main() {
String name = 'Thu'; // can never be null
String? middleName; // may be null; defaults to null
print(name.length);
print(middleName);
// name = null; // compile error
middleName = 'Thi';
print(middleName.length); // OK: Dart knows it's non-null now
}3
null
3
| Type | Can hold |
|---|---|
int |
Any integer, never null |
int? |
Any integer or null |
List<String?> |
A list (never null) whose items may be null |
List<String>? |
A list of non-null strings, or null itself |
Type promotion
Once you check that a local variable isn't null, Dart promotes it to the non-nullable type within that branch. No casts needed.
int describeLength(String? text) {
if (text == null) {
return 0;
}
// text is promoted to String here
return text.length;
}
void main() {
print(describeLength(null));
print(describeLength('hello'));
}0
5
Note: Promotion works for local variables and parameters, and (since Dart 3.2) for private
finalfields. For other fields, copy the value into a local variable first:final user = this.user; if (user != null) { ... }.
Null-aware operators
| Operator | Example | Meaning |
|---|---|---|
?. |
user?.name |
Access only if not null, otherwise the result is null |
?? |
name ?? 'Guest' |
Fallback value if null |
??= |
cache ??= load() |
Assign only if currently null |
! |
maybe! |
"Trust me, it's not null" — throws if it is |
?[] |
list?[0] |
Index only if the collection isn't null |
...? |
[...?extra] |
Spread only if not null |
class Address {
final String city;
Address(this.city);
}
class Customer {
final String name;
final Address? address;
Customer(this.name, [this.address]);
}
void main() {
final a = Customer('Hai', Address('Hue'));
final b = Customer('Ly');
print(a.address?.city);
print(b.address?.city);
print(b.address?.city ?? 'Unknown city');
print(b.address?.city.toUpperCase());
List<int>? scores;
print(scores?[0]);
scores ??= [10, 20];
print(scores[0]);
}Hue
null
Unknown city
null
null
10
Notice b.address?.city.toUpperCase(): if address is null, the whole chain short-circuits to null, so toUpperCase is never called on null.
The ! operator — use with care
! tells the compiler "I know this isn't null". If you're wrong, the program throws at runtime. Use it only when you truly know more than the compiler, and prefer ??, ?. or an if check otherwise.
void main() {
final ages = {'An': 30};
int knownAge = ages['An']!; // safe: we just put it there
print(knownAge);
try {
int missing = ages['Bo']!;
print(missing);
} catch (e) {
print('Oops: $e');
}
}30
Oops: Null check operator used on a null value
late and required
Two keywords help you keep variables non-nullable even when they can't be initialized immediately:
requiredon a named parameter forces callers to pass a value:Profile({required this.userId}).latedefers initialization:late final AnimationController controller;assigned ininitState— a common Flutter pattern. Reading alatevariable before assignment throws aLateInitializationError.
Null-safe patterns
Dart 3 patterns offer two neat tools: the null-check pattern ? and the null-assert pattern !.
String greet(String? name) => switch (name) {
null => 'Hello, stranger',
String n when n.isEmpty => 'Hello, nobody',
final n => 'Hello, $n',
};
void main() {
print(greet(null));
print(greet(''));
print(greet('Phuong'));
String? maybeCity = 'Vinh';
if (maybeCity case final city?) {
print('City has ${city.length} letters');
}
}Hello, stranger
Hello, nobody
Hello, Phuong
City has 4 letters
case final city? matches only when the value is non-null and binds it as a non-nullable String.
Why it matters in Flutter
Flutter APIs are fully null-safe. When you see String? errorText on an InputDecoration, you know null means "no error". When a widget parameter is required, the analyzer won't let you forget it. Data from the network (JSON) is the main place where nulls appear — handle them at the boundary and keep the rest of your app non-nullable.
Test yourself
Which declaration allows a variable to hold null?
- String s;
- String? s;
- late String s;
- final String s;
What does user?.name evaluate to when user is null?
- An exception
- An empty string
- null
- 'null'
What happens when you apply ! to a null value?
- It returns a default value
- It throws at runtime
- It is a compile error
- It returns false