Null Safety
Null Assertion
The null assertion operator ! tells the analyzer 'I know this nullable value is non-null right here', and converts a T? into a T. Use it when you have proven the value is not null but the analyzer cannot see why, for example after a guard check or when reading a value you control. If the value really is null at runtime, ! throws a runtime error, so reach for it sparingly and prefer ??, ?., or a real null check when the value might actually be missing.
Program
Play the program to assert a non-null String? into a String with !, then use the promoted value.
null_assertion.dart
void main() {
String? maybeName = 'Ada';
String name = maybeName!;
var greet = 'Hello, $name';
print('$greet len=${name.length}');
}
!
`maybeName!` asserts the value is not null and promotes the static type from `String?` to `String`. The runtime value is unchanged.
non-null promotion
Once `name` is a `String`, member access like `name.length` is a normal field read with no null check.
warning
If the asserted value really is `null` at runtime, `!` throws a runtime error. Prefer `??`, `?.`, or a real `if (x != null)` when the value might actually be missing.