🎓 A1Learner
🔍
0 of 37 lessons completed

Dart Definite Assignment

Definite assignment means Dart proves a non-nullable local variable gets a value on every path before it is used. The proof happens at compile time, before the program runs.

Assigned in both branches

label is declared with no value. Both branches assign one, so the print after the branches can use label freely.

void main() {
  String label;
  var ready = true;
  if (ready) {
    label = 'on';
  } else {
    label = 'off';
  }
  print(label);
}

The else branch value

passed holds false, so the else branch runs. Its assignment is the one the print shows.

void main() {
  int score;
  var passed = false;
  if (passed) {
    score = 100;
  } else {
    score = 40;
  }
  print(score);
}

One assignment and an early return

The true path returns from inside the if block and never reaches the assignment. The other path assigns result before its own return.

String pick(bool flag) {
  String result;
  if (flag) {
    return 'yes';
  }
  result = 'no';
  return result;
}

void main() {
  print(pick(true));
  print(pick(false));
}

Example

void main() {
  String message;
  var count = 2;
  if (count > 5) {
    message = 'many';
  } else {
    message = 'few';
  }
  print('$message: $count');
}

Key points

  • A non-nullable local variable can be declared without a value when every path assigns one.
  • Assigning in both the if branch and the else branch covers every path.
  • A path that returns early needs no assignment, because the code after it never runs on that path.
  • Dart reports an error when some path can reach the use without an assignment.

In this example, message is declared with no value and both branches assign one. The count 2 fails the test, so the else branch stores few. The print then uses message freely and shows few with the count.

Note

Definite assignment applies to local variables, which no other code can change behind the scenes.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DartPad

Exercise

When can a non-nullable local variable be used without an initializer?