Colon : in Dart constructor syntax

This feature in Dart is called “initializer list”.
It allows you to initialize fields of your class, make assertions and call the super constructor.

This means that it is not the same as the constructor body. As I said, you can only initialize variables and only access static members. You cannot call any (non-static) methods.

The benefit is that you can also initialize final variables, which you cannot do in the constructor body. You also have access to all parameters that are passed to the constructor, which you do not have when initializing the parameters directly in the parentheses.
Additionally, you can use class fields on the left-hand of an assignment with the same name as a parameter on the right-hand side that refers to a parameter. Dart will automatically use the class field on the left-hand side.
Here is an example:

class X {
  final int number;

  X(number) : number = number ?? 0;
}

The code above assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that, but I want to explain how everything works together):

class X {
  final int number;

  X(number): number = number ?? 0, assert(number != null);
}

Learn more.

Leave a Comment