← → or space · progress saves for Continue on the roadmap
Goal
Know which values may be null and let the type system force you to handle absence.
Step 1 - Non-nullable by default
void main() {
String name = 'Asha';
name = 'Rafi';
}Stringcannot holdnull. Assigningnullis a compile error.
Step 2 - Nullable type
void main() {
String? nick = null;
nick = 'Ace';
print(nick);
}T?meansTornull.
Step 3 - Passing between worlds
String requireName(String? input) {
if (input == null) {
return 'Anonymous';
}
return input;
}
void main() {
print(requireName(null));
print(requireName('Asha'));
}- After a null check, Dart promotes
inputtoStringin that branch.
Good habit
- Prefer
Tfor values that must exist; useT?when absence is real data.
Practice tasks
- Change
requireNameto returnString?and returnnullfor empty string after trim. - List three APIs in
dart:corethat return nullable types and why.