Nullable types
- Dart course
- Beginner
- Lesson 71/116
- 5 min
Learn String? and nullable types.
Nullable types
In Dart 3 a type is non-nullable by default. String name; requires name to hold a value. To allow null, append ?: String? name;.
Now name is either a String or null. The question mark says 'this variable may be empty'. Assigning null to a non-nullable type is a compile error.
Nullable types describe 'maybe a value, maybe not' cases. A form field may be left blank, so its type becomes String?. The compiler then warns you about the null risk.
Assigning null
You can directly assign null to a nullable variable: String? name = null;. Leaving it unassigned also defaults to null: String? name; equals String? name = null;.
Be careful when using a nullable variable. Calling name.length throws if name is null. That is why null-aware operators and null checks matter; later lessons cover them.
Once you assign a non-null value, it is safe to use: name = 'Ayşe'; print(name.length);. Still, the compiler may warn about the nullable type; ! or a null check then helps.
Practice Declare nullable and assign
Declare a String? name (starting as null). Then assign name = 'Ayşe' and print it with print(name).
Starter code
void main() {
// declare a nullable variable
// assign 'Ayşe' and print
}Sample solution
void main() {
String? name;
name = 'Ayşe';
print(name);
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the types
| Term | Meaning |
|---|---|
String |
Text, never null |
String? |
Text, may be null |
int |
Number, never null |
int? |
Number, may be null |
2 Which is nullable?
- String? Correct answer
- int
- String
- double
Explanation: String? is a nullable type.
3 Nullable declaration
void main() {
String? ____;
print(name);
}
void main() {
String? name;
print(name);
}
Explanation: the variable name is name.