CodeBlanks Logo Icon CodeBlanks

The ! operator

Learn null assertion with !.

The ! operator

The ! operator performs a null assertion: you say 'I guarantee this value is not null'. name!.length treats name as non-nullable.

If name is actually null, it throws at runtime. So ! is used carefully: only when you are sure the value is non-null.

? and ! are opposites: ? makes a type nullable, ! uses a nullable as non-nullable. In practice null checks are preferred over !, but the bang is sometimes a handy shortcut.

! vs ?.

Both ! and ?. access a member on a nullable value, but they behave differently. ! asserts non-null; if wrong, it throws. ?. returns null when the value is null; no error.

Example: name!.length crashes if name is null; name?.length returns null instead. Which one to pick depends on your task.

Rule of thumb: ! when sure, ?. when not. ! is faster but risky; ?. is safe but yields a nullable result.

Practice Length with !

Declare a String? name and assign 'Ayşe'. Print its length with print(name!.length).

Starter code

main.dart
void main() {
  // declare a nullable and assign 'Ayşe'

  // print length with !
}

Sample solution

main.dart
void main() {
  String? name = 'Ayşe';
  print(name!.length);
}

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does name!.length do when name is null?

  • Returns null
  • Returns 0
  • Throws an error Correct answer
  • Nothing

Explanation: ! throws on a null value.

2 Assertion with !

Question
void main() {
  String? name = 'Ayşe';
  print(name____.length);
}
Answer
void main() {
  String? name = 'Ayşe';
  print(name!.length);
}

Explanation: ! treats the nullable as non-nullable.

3 Match the operators

Term Meaning
! Null assertion
?. Safe access
?? Default value
? Nullable type

All lessons in Beginner