Back to results for “Error Handling”
Flutter › Dart Null Safety

What is the null assertion operator, written as an exclamation mark, and why should it generally be used carefully and only when you are genuinely certain a specific nullable value cannot actually be null at that particular point?

Intermediate

Answer

The null assertion operator, written as a single exclamation mark placed immediately after a nullable expression, tells the Dart compiler that you are personally certain that specific value is genuinely not null at that particular point in your code, even though its declared type technically still permits it to be null, and while this can be useful in situations where you truly know more about the actual runtime state than the compiler's own static type system can determine on its own, using it incorrectly, meaning the value actually does turn out to be null at that point, throws a genuine runtime error, which somewhat undermines one of the core safety benefits that null safety was specifically designed to provide in the first place.
String? userName = fetchCachedUserName();
print(userName!.toUpperCase()); // Throws if userName is actually null
Real-world example A developer uses the null assertion operator on a cached value they have already explicitly verified is not null just a few lines earlier, while carefully avoiding using that same risky operator on a value whose null status genuinely cannot be reliably guaranteed at that point.

Common follow-ups: What are safer alternatives to using the null assertion operator in most typical situations?;What kind of error does using the null assertion operator on an actual null value throw?