Starter lesson
Handle optional text with null safety
External data is often missing or blank. Dart’s nullable types make that uncertainty visible so a function can handle it deliberately.
String displayName(String? value) {
final cleaned = value?.trim();
if (cleaned == null || cleaned.isEmpty) {
return 'Guest';
}
return cleaned;
}
void main() {
print(displayName(' Mira '));
print(displayName(null));
}
What to expect
Mira
Guest
Key idea: Model missing values in the type system instead of relying on assumptions about incoming data.