Null safety
- Dart course
- Beginner
- Lesson 11/116
- 5 min
Learn null and nullable types (?) in Dart.
Null safety
Dart 3 has null safety on by default. A variable cannot be null unless you explicitly say so. This catches unexpected null errors at compile time.
You make a type nullable by adding ? at the end: String? means 'a String or null'. For example String? middleName; can be null.
With this system you get a guarantee: 'this variable is never null'. Nullable types require a null check before use; otherwise the compiler warns you.
Practice Nullable variable
Declare a nullable name variable with String? name = null; and print it with print(name);.
Starter code
// Declare a nullable variableSample solution
void main() {
String? name = null;
print(name);
}Expected output
null
What is null safety for?
The biggest benefit of null safety is that it catches null errors at compile time. In older languages you could not know if a variable was null until you ran the code; Dart tells you at compile time.
This reduces famous errors like 'null pointer exception'. Before using a nullable variable you check with if (x != null) or the ? operator; we will see this in a later lesson.
The result: fewer surprises, safer code. With Dart 3 this is the default; it cannot be turned off.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Null safety concepts
| Term | Meaning |
|---|---|
String |
cannot be null |
String? |
can be null |
null |
no value |
? |
nullable marker |
2 Null value
String? email = ____;
String? email = null;
Explanation: This keyword marks absence of value.
3 What is the difference between String and String?
- They are the same
- String? can be null Correct answer
- String is faster
- String? only in classes
Explanation: The correct answer: String? can be null. String can never be null.