Sub topic 2
Non-nullable by default: T versus T?
This chapter assumes you know basic Dart syntax, including variables, functions, classes and constructors. It also assumes you have used dart run or DartPad. It does not cover the null-aware operators or type promotion in depth, because later chapters do.
The rule: a type name excludes null
In Dart with null safety, writing a type name such as String or int means the value is never null. To allow null, add a question mark to the type: String? or int?. The two forms are different types, and the compiler checks them separately.
void main() {
String name = 'Ada';
String? nickname;
// name = null; // Compile-time error: null is not a String
print(name.length); // 3
print(nickname); // null
print(nickname?.length); // null
}Here nickname is declared without a value. A nullable variable that you do not initialize starts as null. You can assign null to a nullable variable at any time.
The compiler uses these types to decide which operations are legal. You can call name.length freely. You cannot call nickname.length directly, because the value might be null. The compiler rejects that line instead of letting it crash at runtime.
What you can call on a nullable value
A String? value has only the members that every object has, because null has only those members. Those members are toString(), ==, hashCode, runtimeType and noSuchMethod. Calling any other member is a compile-time error until you handle the null case.
void main() {
String? nickname;
print(nickname.toString()); // null (the text "null")
print(nickname == null); // true
print(nickname.hashCode == null.hashCode); // true
}How T and T? relate
A non-nullable type is a subtype of its nullable version. A String is always usable where a String? is expected. The reverse is not true, because a String? might hold null.
bool isObject(Object? v) => v is Object;
void main() {
String a = 'hi';
String? b = a; // OK: String is a subtype of String?
// String c = b; // Error: 'String?' can't be assigned to 'String'
print(b); // hi
print(isObject(null)); // false
print(isObject(1)); // true
}You can think of T? as the union of T and the type Null. Null is a class with exactly one value, null. Two special types sit at the top of the hierarchy:
Object?is the top type. Every value, including null, is anObject?.Objectis the top of the non-nullable types. It excludes null.
The type dynamic still accepts null, because dynamic switches off static checking. This is one reason to avoid it in null-safe code. If you write var x; with no type and no initializer, x is dynamic, not a nullable type.
The same rule at runtime
Type tests follow the same rules. null is int? is true and null is int is false. This also matters for casts. value as int throws if value is null, while value as int? succeeds.
Where non-nullable variables need a value
A non-nullable variable cannot hold null, so Dart requires it to be assigned before you read it. The rules depend on where the variable lives.
| Kind of variable | Non-nullable without an initializer | Nullable without an initializer |
|---|---|---|
| Local variable | Allowed, if every path assigns it before the first read | Starts as null |
| Instance field | Error, unless set by the constructor or marked `late` | Starts as null |
| Top-level or static variable | Error, unless marked `late` | Starts as null |
For local variables, the compiler tracks assignments through your branches:
void main() {
int count; // no initializer, and that is allowed
if (DateTime.now().hour < 12) {
count = 1;
} else {
count = 2;
}
print(count); // OK: every path assigned count
}If one branch skipped the assignment, reading count would be a compile-time error. Fields work differently because the compiler cannot see every place a field is read. Later chapters cover fields in detail, including required parameters, initializer lists and late.
Parameters and return types
The same rule applies to parameters and return values. A parameter that callers must always supply is non-nullable. A parameter that is truly optional is nullable, or it has a default value.
String greet(String name, [String? title]) {
if (title == null) return name;
return '$title $name';
}
String label({required int id, String prefix = 'item'}) => '$prefix-$id';
void main() {
print(greet('Ada')); // Ada
print(greet('Ada', 'Dr.')); // Dr. Ada
print(label(id: 7)); // item-7
}An optional parameter must be nullable or have a default. This declaration is an error because the omitted argument would leave x without a value:
// void f([int x]) {} // Error: x has no default and is not nullable
void f([int x = 0]) {} // OK: default value
void g([int? x]) {} // OK: x is null when omittedA function that might not find a result should return a nullable type. The return type then tells every caller to handle the missing case:
String? firstWord(String text) {
final trimmed = text.trim();
if (trimmed.isEmpty) return null;
return trimmed.split(' ').first;
}
void main() {
print(firstWord('hello world')); // hello
print(firstWord(' ')); // null
}Function types and the placement of ?
For function types, the position of the ? matters. It can apply to the return type or to the whole function:
void main() {
String? Function(int) returnsMaybe = (n) => n > 0 ? 'positive' : null;
String Function(int)? maybeFunction;
print(returnsMaybe(1)); // positive
print(returnsMaybe(-1)); // null
print(maybeFunction == null); // true
}String? Function(int) is always a function, and its result might be null. String Function(int)? might be null itself, and if it is a function, its result is never null. The same placement issue appears with collections, which a later chapter covers.
Choosing between T and T?
Make a type nullable only when "no value" is a meaningful state in your program. Some examples where null is meaningful:
- A user's optional email address.
- The result of a search that may find nothing.
- A value that really is unknown until a later event, such as a response that has not arrived.
Prefer non-nullable types when a value always exists. A nullable type pushes work onto every caller, because each one must handle the null case.
You also have alternatives to null for "nothing here". An empty list often works better than a List<int>?, and a default value often works better than a nullable parameter. Choose null when absence carries a different meaning from empty or zero. For example, an empty string might be a valid name, while null means "not provided".
Common mistakes
- Making everything nullable. This compiles, but every use then needs a null check. It removes most of the benefit of null safety.
- Silencing errors with
!. The!operator tells the compiler to trust you, and a wrong guess throws at runtime. A later chapter covers safer alternatives. - Forgetting that a lookup can fail. A
Maplookup such asages['bob']returns a nullable type, because the key may be missing. - Confusing
T?with a default value. A nullable variable starts as null. It does not start as an empty value such as0or''. - Using
dynamicto avoid the question. It accepts null and also skips every other static check.
Exercise
Which of these lines cause a compile-time error, and why? Assume each line is inside main.
(a) String? a = 'x'; String b = a;
(b) int count; count = 3; print(count);
(c) var n = 5; n = null;
(d) Object? o = null;
Show answer
Lines (a) and (c) are errors. (a) assigns a String? to a String, and the value might be null. (c) infers n as int, which cannot hold null. Line (b) is fine because count is assigned before it is read. Line (d) is fine because Object? is the top type and accepts null.
Exercise
A function findUser(int id) looks a user up in a database. It sometimes finds no user. Which return type is better, User or User?, and what does the choice force on callers?
Show answer
User? is better, because "no user found" is a normal outcome. The nullable return type forces every caller to handle the null case before using the user. Returning a non-nullable User would require a fake or throwing value to cover the not-found case.