Declaring Nullable Variables
String? username; // null by default
int? age = null; // explicitly null
double? score = 98.5; // has a value, but could be null later
// Nullable parameters in functions
void printName(String? name) {
print(name ?? 'Anonymous');
}
printName(null); // Anonymous
printName('Alice'); // Alice
Null Checks
Before using a nullable variable, check if it is null:
String? email = getUserEmail(); // might return null
// Method 1: if check (promotes to non-nullable inside if)
if (email != null) {
print(email.toUpperCase()); // safe — email is String here
}
// Method 2: ?? operator
print(email ?? 'no-email@example.com');
// Method 3: ?. null-aware access
print(email?.toLowerCase());
Inside an if (variable != null) check, Dart automatically promotes the nullable type to its non-nullable counterpart:
String? text = maybeGetText();
if (text != null) {
// Here, text is treated as String (not String?)
// All String methods are available without ?
int len = text.length; // no error
print(text.toUpperCase());
}
Example
String? getUserEmail() => 'user@example.com';
int? getAge() => null;
void main() {
String? email = getUserEmail();
int? age = getAge();
// Pattern: check and use
if (email != null) {
print('Email domain: $${email.split("@").last}');
}
// Pattern: provide default
int userAge = age ?? 0;
print('Age: $userAge'); // 0
// Pattern: early return
void processAge(int? a) {
if (a == null) { print('Age unknown'); return; }
print('In $${18 - a} years you will be 18');
}
processAge(age); // Age unknown
processAge(14); // In 4 years you will be 18
}
Output:Email domain: example.com
Age: 0
Age unknown
In 4 years you will be 18
🧠 Quiz
1. What is type promotion in Dart?
- A) Converting int to double
- B) Dart treating a nullable as non-nullable after a null check ✅
- C) Casting with as
- D) Upgrading a variable type
Summary
Nullable variables hold either a value or null. Always check with if (x != null), ??, or ?. before using them. Dart's type promotion automatically narrows the type inside null checks so you can use all non-nullable methods safely.