Null safety
โ Report an issue with this lessonString title = "HTML Fundamentals"; // cannot be null
String? subtitle; // nullable, explicitly marked
print(subtitle?.length); // safe access, prints null if subtitle is null
print(subtitle ?? "No subtitle"); // fallback if null
Like Kotlin and Swift, Dart requires you to opt in to nullability
explicitly with ? -- the compiler won't let a
non-nullable variable ever hold null.
Beyond ?. (safe access) and ?? (fallback
value), Dart has a few more null-safety operators worth knowing:
String? subtitle;
subtitle ??= "Untitled"; // assign only if subtitle is currently null
print(subtitle!.length); // "!" (the bang operator) asserts "trust me, this isn't null"
The ! operator is a promise to the compiler, not a
safety check -- if the value actually is null at runtime,
your program throws an exception immediately. Reach for it only when
you're certain (for example, right after an explicit
if (subtitle != null) check that Dart's analyzer can't
otherwise see through), and prefer ?./??
wherever possible since they can never blow up at runtime.
Nullability also applies to class fields, and it interacts directly
with constructors. A non-nullable field must be initialized -- either
with a default value, in the constructor parameter list, or marked
required:
class Course {
final String title; // non-nullable: must always be set
final String? subtitle; // nullable: optional, defaults to null if omitted
final double price;
Course({
required this.title,
this.subtitle, // no `required` -- nullable fields can be safely left out
required this.price,
});
}
final c = Course(title: "Dart Mastery", price: 149.99); // subtitle defaults to null
print(c.subtitle ?? "No subtitle");
This is also why null safety is such a big deal for Flutter apps
specifically: a huge share of real-world mobile app crashes historically
came from a value the developer assumed would be present turning out to
be null at runtime (a network response that failed, a
widget that hasn't loaded yet). Dart's sound null safety catches the vast
majority of these at compile time instead of in a crash report from a
user's device.
Try it yourself
No subtitle
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: a course catalog โ plus a certificate are waiting.
Unlock the full course โ $149.99