Sub topic 2
Non-nullable by Default: `T` Versus `T?`
This chapter assumes you know basic Dart variables, functions, classes, constructors, static types, and type inference. You should also be able to run a Dart program with dart run or DartPad.
Why nullability is part of a type
null means that a value is absent. In older code, any reference could unexpectedly contain null. Calling a method through that reference then caused a runtime error.
Dart's sound null safety makes absence explicit in the type:
Stringmeans a value must always be aString.String?means a value can be aStringornull.intandint?are different types.- A value of type
String?cannot be used wherever Dart requires aStringuntil you handle the possiblenull.
The ? is part of the type declaration. It does not mean that a value is usually present. It records a guarantee that the compiler checks.
void main() {
String name = 'Ada';
String? nickname;
// name = null; // Compile-time error: null is not a String
print(nickname); // null
print(nickname ?? 'none'); // none
nickname = 'Ace';
print(nickname); // Ace
}A non-nullable variable must receive a non-null value before it is read. This rule applies even when the variable is declared without an initial value.
void main() {
String message;
// print(message); // Compile-time error: message is not initialized
message = 'Ready';
print(message);
}Choosing `T` or `T?`
Use T when the program requires a value for the object to be valid. Use T? when absence is a meaningful, supported state.
| Declaration | Meaning |
|---|---|
| `String title` | Every valid object has a title |
| `String? subtitle` | A subtitle may be absent |
| `List<String>` | The list contains only non-null strings |
| `List<String?>` | The list may contain null elements |
For example, an email address might be optional, but a user's name might be required:
class User {
final String name;
final String? email;
User({required this.name, this.email});
}
void main() {
final user = User(name: 'Ada');
print(user.name);
print(user.email ?? 'no email');
}The required keyword makes the named name argument mandatory. Because name is non-nullable, the constructor must ensure that it is initialized with a String.
A nullable value is not automatically converted to its non-nullable version. This fails:
void printName(String? name) {
// print(name.length); // Error: name may be null
}The compiler is protecting the code from a possible invalid method call. Handle the two possible states explicitly:
int lengthOrZero(String? text) {
if (text == null) {
return 0;
}
return text.length;
}
void main() {
print(lengthOrZero(null)); // 0
print(lengthOrZero('Dart')); // 4
}After the if statement returns for null, Dart's flow analysis promotes text from String? to String in the remaining code.
The type relationship
Think of T? as a wider set of possible values than T:
You can safely use a String where a String? is expected, because every String is also an allowed String?. The reverse is unsafe because the nullable value might be null.
Exercise
Exercise
What is the correct type for a Book field when every book must have a title, but a book may have no publication date?
Show answer
Use final String title; and final DateTime? publishedAt;. The title is required, while the publication date can be absent.