Dart Null Assert
The null assert operator is an exclamation mark written after a nullable value. It tells Dart to treat that value as a non-null value.
An assert on a present value
name holds a text value and the assert follows the name. print shows the stored text.
void main() {
String? name = 'Ana';
print(name!);
}An assert before a length read
word holds a text value, so the assert lets the length read run. print shows the length 4.
void main() {
String? word = 'dart';
print(word!.length);
}The safe way with a fallback
name holds null and the fallback handles that case. print shows Guest.
void main() {
String? name;
print(name ?? 'Guest');
}Example
void main() {
String? city = 'York';
print(city!);
print(city!.length);
}Key points
- Use ! after a nullable value to assert that the value is not null.
- An assert does not change the stored value.
- An assert does not check the value first.
- An assert on a value that holds null stops the program.
- The safe operators from the last lesson handle null without an assert.
In this example, city holds the text York. The assert after city lets the first print show York. The assert in the next line lets the length read run. The last print shows 4.
Note
Use ! only when the value is certain to be present.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
When is the assert operator safe to use?