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 (): Asserts a nullable value is not nulltext
! - Null-aware operators (,text
?.,text??,text??=): Safely handle potentially null valuestext...?
Null-Check Operator (text!
) -- Force Unwrap
text
!The
text
!text
Null check operator used on a null valuedartString? 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
text
?.dartString? 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
text
??dartString? 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
text
??=dartString? 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
text
...?dartList<int>? extras = null; final list = [1, 2, ...?extras]; // [1, 2] -- null extras ignored
Comparison Summary
| Operator | Name | Safe? | Throws if null? |
|---|---|---|---|
text | Null assertion | NO | Yes -- throws |
text | Safe access | Yes | No -- returns null |
text | Null coalescing | Yes | No -- uses default |
text | Null assignment | Yes | No -- assigns if null |
text | Null-aware spread | Yes | No -- skips |
Rule: Avoid
unless you are 100% certain the value cannot be null. Prefertext!andtext?.for safe, crash-free null handling.text??