D
Dart LanguageEasy20 XP5 min read

How does Dart's sound null safety work?

TL;DR: Dart's sound null safety means non-nullable types can never be null at runtime — the compiler enforces this statically, eliminating null pointer exceptions. Nullable types are denoted with ?, and the compiler tracks nullability through control flow.

Full Answer

Dart's null safety is 'sound' — the type system guarantees that if a variable is typed String (not String?), it will never be null at runtime. The compiler performs flow analysis to track when nullable types have been proven non-null.

Null-aware operators

  • ?. (null-conditional): obj?.method() — returns null if obj is null
  • ?? (null-coalescing): value ?? default — returns default if value is null
  • ??= (null-aware assignment): x ??= 5 — assigns 5 only if x is null
  • ! (null assertion): value! — asserts non-null, throws if null
  • late: defers initialization, guarantees non-null before first use
⚠️

The ! operator (null assertion) throws a Null check operator used on a null value at runtime if the value IS null. Use it only when you are 100% certain the value is non-null. Prefer null-safe alternatives.

Code Examples

dartNull safety operators in practice
Output
null
default
5
5
[throws LateInitializationError if setName not called]
[throws: Null check operator used on a null value]

Interview Tip

💡

Sound null safety means null safety is not 'best-effort' — the compiler proves at compile time that non-nullable variables will never be null. This eliminates a whole class of runtime errors.

#null-safety#nullable#non-nullable#late#null-aware