Skip to content
Dart

Null Safety

Sound null safety with ? and ! operators.

By EZ4Code Team
null-safetynullable

Code

// Non-nullable (default)
String name = 'Alice';
// name = null;  // compile error!

// Nullable
String? maybeName;
maybeName = null;  // OK

// Null assertion (!) — crashes if null
int len = maybeName!.length;  // unsafe

// Null-aware access (?.) — returns null if null
int? safeLen = maybeName?.length;

// Null-coalescing (??) — default if null
int lenOrDefault = maybeName?.length ?? 0;

// Late (initialized later, but non-nullable)
class Service {
  late final Config config;  // set before first use
  void init(Config c) { config = c; }
}

// Required (named params, non-null)
void greet({required String name}) => print('Hi $name');

// Promotion (smart casts)
String? getName() => DateTime.now().second % 2 == 0 ? 'Bob' : null;
void main() {
  var n = getName();
  if (n != null) {
    print(n.length);  // safe — Dart promotes
  }
}

Explanation

Dart's sound null safety: types are non-nullable by default. ? marks nullable; ! asserts non-null (throws if wrong); ?. is safe access; ?? provides default. late defers initialization (you promise to set before use). required forces callers to pass named args. Smart promotion: after `if (x != null)`, x is treated as non-null — no explicit cast needed.

More Dart Snippets