🎓 A1Learner
🔍
0 of 37 lessons completed

Dart Type Promotion

Type promotion means Dart treats a nullable variable as non-nullable after a check proves it holds a value. The promoted type holds only inside the checked region.

A parameter promotes inside the check

Inside the if block, name is treated as a plain String. The method call runs for the text value and is skipped for null.

void shout(String? name) {
  if (name != null) {
    print(name.toUpperCase());
  }
}

void main() {
  shout('ana');
  shout(null);
}

Length after a passing check

The if branch runs only when word holds a value, so the length read is safe there. The else branch handles the null case.

void showLength(String? word) {
  if (word != null) {
    print(word.length);
  } else {
    print('no word');
  }
}

void main() {
  showLength('dart');
  showLength(null);
}

The early return guard

The guard returns at once when name holds null. Every line after the guard can treat name as a plain String.

void greet(String? name) {
  if (name == null) {
    print('Hello, guest');
    return;
  }
  print('Hello, $name');
}

void main() {
  greet(null);
  greet('Ana');
}

A field copied into a local

The field city does not promote, so the program copies it into a local variable first. The local promotes inside the check and the method call runs.

class Profile {
  String? city;
}

void main() {
  var profile = Profile();
  profile.city = 'York';
  var city = profile.city;
  if (city != null) {
    print(city.toUpperCase());
  }
}

Example

void describe(String? word) {
  if (word == null) {
    print('missing');
    return;
  }
  print(word.length);
  print(word.toUpperCase());
}

void main() {
  describe(null);
  describe('dart');
}

Key points

  • After a null check passes, a parameter or local variable promotes to its non-nullable type.
  • Inside a passing check, the variable works as a plain String, so length and methods are available.
  • An early return guard also promotes the code that follows it for the rest of the function.
  • Fields of a class do not promote, because another part of the program could change them between the check and the use.
  • Copying a field into a local variable gives a value that does promote.

In this example, the guard sends the null call out of the function after one print. The second call passes the guard, so word is promoted for the rest of the function. The length print shows 4 and the last print shows DART.

Note

Promotion ends where the checked region ends.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DartPad

Exercise

Why does a class field not promote after a null check?