Michael Gao
Michael Gao

Reputation: 63

Dart/Flutter super(key:key) example

Take this code for a constructor for a stateful widget:

  MyHomePage({Key key, this.title}) : super(key: key);

Is this the same as writing the following:

MyHomePage(Key key, String title) {
     super(key);
     this.title = title;
}

Furthermore, I understand that the first ':' starts the initializer list, or the functions that must be called before the constructor at hand -- in this case, "MyHomePage".

Is there any situation where there are other functions there other than - or in addition to - super?

Upvotes: 1

Views: 2171

Answers (1)

osaxma
osaxma

Reputation: 3004

For the first question:

No, it wouldn't work because the super class was already constructed, and you'll get this error: The expression doesn't evaluate to a function, so it can't be invoked

For the second question:

Beside initializing fields and calling the constructor of the super class, assertions are also used in the initializer list during development (see when it works here), for example:

import 'dart:math';

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(x, y)
      : assert(x < y),
        x = x,
        y = y,
        distanceFromOrigin = sqrt(x * x + y * y);
}

main() {
  var p = new Point(2, 3);
  print(p.distanceFromOrigin);
}

Reference: Language Tour - Initializer List

Upvotes: 2

Related Questions