CodeBlanks Logo Icon CodeBlanks

Null check

Learn null checking with if (x != null).

Null check

The safest null handling is the if (x != null) check. Inside this block x is treated as non-nullable; this is called type promotion.

Example: String? name = 'Ayşe'; if (name != null) { print(name.length); }. Inside the block name is non-null, so .length is safe.

This pattern is safer than ! or ?. because it checks explicitly and guarantees the type inside the block. In complex conditions Dart may narrow the guarantee; then ! helps.

Limits of promotion

Type promotion works in most cases but has limits. If a variable can be mutated inside a lambda, Dart may drop the guarantee inside the block. Then ! or a local copy is needed.

Example: String? name = 'Ayşe'; if (name != null) { var f = () => print(name); }. Here the lambda could mutate name later, so Dart drops the guarantee.

In practice this is rare. Simple if (x != null) blocks promote safely. For complex cases ! or a local copy can rescue you.

Practice Length with null check

Declare a String? name and assign 'Ayşe'. Check with if (name != null); inside the block add a print(name.length) call.

Starter code

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

  // null check with if and print length
}

Sample solution

main.dart
void main() {
  String? name = 'Ayşe';
  if (name != null) {
    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 is name inside if (name != null)?

  • String (non-nullable) Correct answer
  • null
  • Still String?
  • Throws

Explanation: after the null check the type is non-nullable.

2 Match the null methods

Term Meaning
if (x != null) Type promotion
?. Safe access
! Null assertion
?? Default value

3 Null check with if

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

Explanation: != sets the 'not null' condition.

All lessons in Beginner