Summary - Null safety
- Dart course
- Beginner
- Lesson 76/116
- 5 min
Combine ?, ??, ! and late to write a null-safe function.
Summary - Null safety
This group covered Dart 3 null safety basics. ? makes a type nullable; ?? gives a default, ?. accesses safely, ??= assigns if null.
! asserts non-null; use it when sure. late defers a non-nullable initialization. if (x != null) with type promotion is the safest route.
In the final task you will combine ?, ?? and !. You will declare a nullable variable, print it with a default, then assign and call ! on its length.
Practice Print with default
Declare a String? title (starting as null). Print it with print(title ?? 'Bay').
Starter code
void main() {
// declare a nullable variable
// print with a default
}Sample solution
void main() {
String? title;
print(title ?? 'Bay');
}Expected output
Bay
Practice Combining ? and !
Declare a String? name (starting as null). Print it with print(name ?? 'Misafir'). Then assign name = 'Ayşe' and print its length with print(name!.length).
Starter code
void main() {
// declare a nullable variable (null)
// print with a default, then assign 'Ayşe' and print length with !
}Sample solution
void main() {
String? name;
print(name ?? 'Misafir');
name = 'Ayşe';
print(name!.length);
}Expected output
Misafir 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Using ??
void main() {
String? name;
print(name ____ 'Misafir');
}
void main() {
String? name;
print(name ?? 'Misafir');
}
Explanation: ?? returns the right side when the left is null.
2 Match the operators
| Term | Meaning |
|---|---|
? |
Nullable type |
?? |
Default value |
!. |
Access with assertion |
late |
Deferred init |
3 Which performs a null assertion?
- ?.
- ! Correct answer
- ??
- ??=
Explanation: ! is the null assertion operator.