Sub topic 6
The ! operator: when to use it and when not to
This chapter assumes you know Dart's T versus T? types, the null-aware operators ?. and ??, and how a null check promotes a local variable. You should also be able to run Dart code with dart run or in DartPad.
What the ! operator does
The null assertion operator is a postfix !. It takes an expression of type T? and gives you the same value with type T. The compiler accepts this on trust and inserts a runtime check. If the value is null, the program throws a TypeError.
String? find(bool exists) => exists ? 'Dart' : null;
void main() {
String sure = find(true)!;
print(sure.length); // 4
try {
print(find(false)!.length);
} on TypeError catch (e) {
print('Caught: $e'); // Caught: Null check operator used on a null value
}
}The compiler has no objection to find(false)!. It cannot know what find returns for a given argument, so it relies on your claim. If the claim is wrong, you get a crash at runtime, which is the failure null safety was designed to prevent.
The ! operator does not stop null errors. It turns a compile-time check into a runtime check that you wrote yourself.
Reading ! in expressions
The operator binds tightly to the expression on its left. Where you put it decides what you are asserting.
| Expression | What is asserted non-null | Result type when `list` is `List<int?>?` |
|---|---|---|
| `list!` | the list itself | `List<int?>` |
| `list![0]` | the list only | `int?` |
| `list![0]!` | the list and the element | `int` |
| `list?[0]!` | the element, and the list gets a null-safe access | `int` |
The last row can still throw. If list is null, list?[0] evaluates to null, and then ! throws. Writing ?[ before ! does not make the expression safe.
The operator also differs from boolean negation. !flag is a prefix operator on bool. value! is postfix on any nullable type. The two never conflict, because the position of the ! tells the parser which one you mean.
The cost of using it
Each ! marks a place where the compiler stopped helping you. Three things follow.
- Failures are far from their cause. The thrown error says only "Null check operator used on a null value". It does not name the variable or the reason it was null.
- The assumption is invisible. Code that was correct when written can break when someone changes a function two files away.
- It can hide a design problem. If you need
!on a value everywhere, the type may be wrong, or the data may be initialized in the wrong place.
A ! on a value that is already non-nullable is useless, and the analyzer reports it as unnecessary_non_null_assertion. This often appears after a refactor makes a variable non-nullable. Remove the ! when you see it.
Promotion after !
For a local variable, x! also promotes x for the rest of the scope. If the assertion passes, the compiler knows x is not null afterwards.
String? readName() => 'Ada';
void main() {
String? s = readName();
print(s!.length); // 3, throws here if s is null
print(s.length); // 3, s is now promoted to String
}Only the first use needs the !. Writing s! on every line is noise, and it is the usual sign of code that should have used a null check or a local variable.
Safer alternatives
Before writing !, decide what should happen when the value is null. Each answer has a more precise tool.
| If null should... | Use | Example |
|---|---|---|
| produce a default | `??` | `name ?? 'guest'` |
| skip the operation | `?.` | `user?.save()` |
| be handled in a branch | null check and promotion | `if (x == null) return;` |
| be reported with a clear error | explicit `throw` | `if (x == null) throw StateError('...')` |
| be impossible by construction | change the type | make the field `final` and required |
| be set later, before first use | `late` | `late final Config config;` |
The explicit throw replaces the vague error with a useful one:
class Connection {
String? _host;
void open(String host) {
_host = host;
}
String describe() {
final host = _host;
if (host == null) {
throw StateError('Call open() before describe()');
}
return 'Connected to $host';
}
}
void main() {
final c = Connection();
try {
c.describe();
} on StateError catch (e) {
print(e.message); // Call open() before describe()
}
c.open('example.com');
print(c.describe()); // Connected to example.com
}This version throws just as _host! would, but the message names the cause and the fix. It also copies the field into a local variable, which is what lets the compiler promote it.
The same idea works in one line when the null case is an error. A throw is an expression, so it can be the right side of ??:
String requireName(Map<String, String> row) {
return row['name'] ?? (throw FormatException('Missing "name" column'));
}
void main() {
print(requireName({'name': 'Ada'})); // Ada
}Fields and why ! tempts you
Instance fields are the most common reason people reach for !. The compiler cannot promote a mutable field, because another call could change it between your check and your use. The tutorial's earlier chapter on field promotion covers the cause. For this chapter, what matters is that ! is not the only fix.
class Session {
String? token;
int tokenLengthBad() {
return token!.length; // compiles, throws if token is null
}
int tokenLength() {
final t = token;
if (t == null) return 0;
return t.length;
}
}
void main() {
final s = Session();
print(s.tokenLength()); // 0
s.token = 'abc123';
print(s.tokenLength()); // 6
}Since Dart 3.2, a private final field in the same library can be promoted directly, because the compiler can see that nothing else changes it. If you control the class, making a field final and private often removes the need for both ! and the local copy.
When ! is the right tool
Some uses are legitimate. The common thread is that you hold knowledge the type system cannot express, and a failure would mean a bug in your program.
- A key you just checked. After
containsKey, the map lookup cannot be null if the value type is non-nullable, but[]still returnsV?. - An invariant guaranteed by a framework. Some APIs return a nullable type that is non-null whenever you use them in the documented way.
- Tests and scripts. A crash on null is an acceptable failure in a test, where it signals a broken expectation.
- After a check the compiler cannot follow. A helper function such as
isReady()may guarantee a value exists, but the compiler does not see inside it.
void main() {
final stock = <String, int>{'apples': 4, 'pears': 0};
if (stock.containsKey('apples')) {
final count = stock['apples']!; // safe: the key was just checked
print(count); // 4
}
}Even here, there is a form that needs no !. Reading the value into a local and checking it is not much longer:
void main() {
final stock = <String, int>{'apples': 4, 'pears': 0};
final count = stock['apples'];
if (count != null) {
print(count); // 4
}
}This version also handles the case where the key is missing, which the containsKey version does not.
A Map whose value type is itself nullable makes ! more dangerous. In a Map<String, int?>, m['a']! throws when the key is missing and also when the key is present with a null value. The two cases are indistinguishable at that point.
Choosing at the keyboard
The diagram shows the decision to make each time you are about to type !.
When you do use !, add a short comment stating the invariant. A reader then knows the assertion was deliberate, and they know what to verify if it ever fails.
Common mistakes
- Silencing the analyzer. Adding
!to make an error go away, without asking why the value is nullable. - Repeating it. Writing
x!on several lines when one assertion would promote a local variable. - Asserting on user or network data. Input from outside your program can be null or missing for reasons you do not control. Validate it and report a useful error instead.
- Catching the TypeError. Wrapping
!intry/catchto handle null is a sign that anifwas needed. ATypeErrorindicates a program bug and should not be used for control flow. - Assuming
?.makes!safe. As shown in the table above,a?.b!still throws whenais null.
Summary
The ! operator converts T? to T and throws a TypeError if the value is null. It promotes local variables after it passes. Use ??, ?., a null check, a clearer throw, or a better declaration first. Keep ! for cases where you know something the compiler cannot, and say so in a comment.
Exercise
This method compiles but can crash. Rewrite it so a missing key gives the message "No price for <item>" through an ArgumentError, with no use of !.
double priceOf(Map<String, double> prices, String item) {
return prices[item]!;
}
Show answer
Read the lookup into a local variable and check it, which also promotes it: double priceOf(Map<String, double> prices, String item) { final price = prices[item]; if (price == null) { throw ArgumentError('No price for $item'); } return price; } A one-line form also works: return prices[item] ?? (throw ArgumentError('No price for $item'));
Exercise
Given List<int?>? values, what is the type of each expression, and which of them can throw when values is null? (a) values! (b) values![0] (c) values?[0]!
Show answer
(a) List<int?>, and it throws when values is null. (b) int?, and it throws when values is null, because the list itself is asserted. (c) int, and it throws when values is null, because values?[0] becomes null and the final ! rejects it. It also throws when the list is non-null but element 0 is null.