What is the Null Assertion Operator?
The null assertion operator ! tells Dart: "I know this nullable value is not null right now — trust me." It converts a nullable type (T?) to a non-nullable type (T) at runtime. If the value IS null, it throws a Null check operator used on a null value error.
Syntax
String? name = 'Alice';
String nonNullable = name!; // asserts name is not null
print(nonNullable.length); // 5
When to Use It
Use ! only when you are absolutely certain the value cannot be null at that point, and the type system cannot figure it out automatically:
// Example: you queried a database and know the record exists
Map<String, String> cache = {'userId': 'abc123'};
String userId = cache['userId']!; // you know this key exists
print(userId); // abc123
// Example: widget keys in Flutter
String? _text;
void initState() {
_text = 'initialized';
}
// Later in build:
print(_text!); // safe after initState ran
⚠️ Danger: Runtime Error
If the value is actually null, ! throws at runtime — which is exactly the kind of crash null safety is meant to prevent:
String? name = null;
print(name!); // RUNTIME ERROR: Null check operator used on a null value
// Prefer safe alternatives:
print(name ?? 'default'); // safe
if (name != null) print(name); // safe
Example
void main() {
List<String> items = ['apple', 'banana', 'cherry'];
// indexOf returns -1 if not found, but here we know it exists
int? idx;
for (int i = 0; i < items.length; i++) {
if (items[i] == 'banana') { idx = i; break; }
}
// We know idx is set — assert it
print('banana is at index $${idx!}'); // 1
// Safe version (better practice)
print('banana is at index $${idx ?? -1}');
}
Output:banana is at index 1
banana is at index 1
📝 Best Practice: Prefer ?? and ?. over !. Use ! only as a last resort when you have domain knowledge that guarantees non-null and the type system cannot infer it.
🧠 Quiz
1. What does name! do if name is null?
- A) Returns null
- B) Returns empty string
- C) Throws a runtime error ✅
- D) Compiles but warns
Summary
The null assertion operator ! converts T? to T at runtime. Use it sparingly — only when you are 100% certain the value is not null. If the value is null, it throws immediately. Prefer ??, ?., or null checks for safer code.