Sub topic 6
The `!` operator: when to use it and when not to
This chapter assumes you know Dart variables, functions, classes, constructors, static types, and basic null-aware operators. You should also be able to run a Dart program with dart run or DartPad.
What `!` means
Dart uses the null assertion operator, written !, to tell the compiler that a nullable value is not null at this point.
String? name = 'Ada';
String nonNullableName = name!;
print(nonNullableName);The type of name is String?, so Dart normally does not allow it where a String is required. The expression name! has type String. It asserts that name contains a value.
The assertion is checked at runtime. If name is null, the program throws an exception instead of continuing.
void main() {
String? name;
print(name!.length); // Throws at runtime.
}The compiler accepts this code because the assertion is explicit. The compiler does not prove that the value is non-null. You are taking responsibility for that fact.
Prefer checks and null-aware operations
Use a null check when the null case is possible and needs a meaningful result.
int lengthOrZero(String? text) {
if (text == null) {
return 0;
}
return text.length;
}After the early return, Dart promotes text from String? to String. This is safer than using text!.length because the null case is handled directly.
Use ?. when the whole operation is optional, and use ?? when you have a fallback.
void showNickname(String? nickname) {
final length = nickname?.length ?? 0;
print('Nickname length: $length');
}Here, nickname?.length produces null when there is no nickname. The ?? 0 expression supplies a value for that case.
Use ??= when a nullable variable should receive a default only when it is null.
void main() {
String? label;
label ??= 'Untitled';
print(label);
}These operators describe the behavior of the program. The ! operator only makes an assertion.
When `!` can be reasonable
A ! operator can be appropriate when a nearby invariant guarantees the value and expressing that invariant with the current API is difficult.
For example, a map lookup returns a nullable value because the key might be absent. If the program has already established that the key exists, ! can make that fact explicit.
String findRequired(Map<String, String> values, String key) {
if (!values.containsKey(key)) {
throw StateError('Missing required key: $key');
}
return values[key]!;
}
void main() {
final settings = {'mode': 'dark'};
print(findRequired(settings, 'mode'));
}The check and the assertion are close together. If the map is changed between those operations by another part of the program, the assumption could still fail. In ordinary single-isolate code, this pattern is usually understandable, but a method that returns or throws directly can often be clearer.
Common failure modes
A ! assertion fails when the value is null at runtime. Common causes include:
- A value came from user input, a file, a network response, or a map.
- A field was expected to be initialized but was not.
- A future refactor changed the condition that guaranteed non-nullness.
- The assertion was added only to silence a compile-time error.
The last case is especially risky. If you cannot explain why the value is non-null, do not use !. Change the control flow, provide a fallback, return a nullable result, or throw a deliberate error with useful context.
A practical rule
First try these options:
- Add an
if (value == null)check. - Use
?.,??, or??=. - Reshape the function so it returns a nullable value or throws a named error.
- Copy a nullable field to a local variable so flow analysis can promote it.
- Use
!only when a clear invariant proves that null is impossible.
Exercise
What happens when String? title is null and the code evaluates title!.length? When is title?.length ?? 0 safer?
Show answer
The ! expression throws a runtime exception because it asserts a false condition. title?.length ?? 0 is safer when null is an expected possibility because it returns 0 instead of throwing.