Question #218EasyDart BasicsImportant

Flutter difference between null check operator and null aware operator ?

#flutter

Answer

Overview

In Dart, there are two distinct concepts for dealing with null:

  • Null-check operator (
    text
    !
    )
    : Asserts a nullable value is not null
  • Null-aware operators (
    text
    ?.
    ,
    text
    ??
    ,
    text
    ??=
    ,
    text
    ...?
    )
    : Safely handle potentially null values

Null-Check Operator (
text
!
) -- Force Unwrap

The

text
!
operator asserts that a value is not null. It throws a
text
Null check operator used on a null value
exception if it IS null.

dart
String? name = null;

// Force unwrap -- DANGEROUS if null
print(name!.length); // THROWS at runtime if name is null

// Safe to use only when you are 100% certain
String? cachedToken = getCachedToken();
if (cachedToken != null) {
  final token = cachedToken!; // Safe here -- checked above
}

// Compiler promotes: no ! needed after null check
String? value = 'hello';
if (value != null) {
  print(value.length); // No ! needed -- compiler knows it's non-null
}

Null-Aware Operators -- Safe Access

text
?.
-- Conditional Member Access

dart
String? name = null;
print(name?.length);       // null (no crash)
print(name?.toUpperCase()); // null

// Chained
User? user = null;
print(user?.address?.city); // null -- safe, no crash

text
??
-- Null Coalescing

dart
String? name = null;
String display = name ?? 'Guest'; // 'Guest'

int? count = null;
int total = count ?? 0; // 0

// Chain
String result = a ?? b ?? c ?? 'default';

text
??=
-- Null Assignment

dart
String? cache;
cache ??= 'loaded data'; // Assigns only if null
print(cache); // 'loaded data'

cache ??= 'overwrite'; // Already non-null -- no change
print(cache); // 'loaded data'

text
...?
-- Null-Aware Spread

dart
List<int>? extras = null;
final list = [1, 2, ...?extras]; // [1, 2] -- null extras ignored

Comparison Summary

OperatorNameSafe?Throws if null?
text
!
Null assertionNOYes -- throws
text
?.
Safe accessYesNo -- returns null
text
??
Null coalescingYesNo -- uses default
text
??=
Null assignmentYesNo -- assigns if null
text
...?
Null-aware spreadYesNo -- skips

Rule: Avoid

text
!
unless you are 100% certain the value cannot be null. Prefer
text
?.
and
text
??
for safe, crash-free null handling.