Anton Duzenko
Anton Duzenko

Reputation: 2596

Dart argument syntax - explanation needed

I accidentally typed something weird and it compiled but caused a type runtime error

class BoldText extends Text {
  BoldText(
    String data, {
    textAlign: TextAlign,
  }) : super(
          data,
          textAlign: textAlign,
        );
}

You can kinda guess what language I come from.

But what is this part supposed to mean?

textAlign: TextAlign

IDE hint shows

{dynamic textAlign: TextAlign}

Which again I fail to decipher.

Upvotes: 0

Views: 35

Answers (1)

lrn
lrn

Reputation: 71633

The textAlign parameter is an optional named parameter. You can specify the default value of a named parameter as either = value or : value. The former syntax is now the preferred one, but the latter is still valid.

If you omit the type of any (normal) parameter of a method or constructor, then it defaults to dynamic.

So, effectively, the declaration of that parameter is { dynamic textAlign = TextAlign }, which is a named parameter with name textAlign, type dynamic and default value TextAlign.

(The "(normal) parameter" above is there to exclude initializing formal parameters like MyConstructor(this.myField) which gets its type from the field it initializes instead of defaulting to dynamic).

Upvotes: 1

Related Questions