Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon after Constructor in dart

This code is from flutter gallery and i'm trying to understanding and adapting it. I would know what this syntax means:

class DemoItem<T> {
  DemoItem({
    this.valueName,
    this.hintName,
    this.valueSurname,
    this.hintSurname,
    this.builder,
    this.valueToString

  }) : textController = new TextEditingController(text: valueToString(valueName));

Especially i would know what means the colon after the constructor and if there is a way to define another TextEditingController, in addition to the one already defined.

like image 526
vila994 Avatar asked May 10 '18 13:05

vila994


2 Answers

The part after : is called "initializer list. It is a ,-separated list of expressions that can access constructor parameters and can assign to instance fields, even final instance fields. This is handy to initialize final fields with calculated values.

The initializer list is also used to call other constructors like : ..., super('foo').

Since about Dart version 1.24 the initializer list also supports assert(...) which is handy to check parameter values.

The initializer list can't read from this because the super constructors need to be completed before access to this is valid, but it can assign to this.xxx.

Pointing out as mentioned in the comments by user693336:

This also means the initializer list is executed before the constructor body. Also the initializer lists of all superclasses are executed before any of the constructor bodies are executed.

Example (copied from https://github.com/dart-lang/language/issues/1394):

class C {
  final int x;
  final int y;
  C(this.x) : y = x + 1;
}
like image 130
Günter Zöchbauer Avatar answered Nov 18 '22 21:11

Günter Zöchbauer


To elaborate on other answers and to complete the syntax, it is also possible to have a real body for the constructor along with initializer code

NonNegativePoint(this.x, this.y) : assert(x >= 0), assert(y >= 0) {
    print('I just made a NonNegativePoint: ($x, $y)');
}

^ Here the assertions happen before the execution of the body

Another use case is to assign values to final fields before body executes

final num x;
final num y;

Point.fromJson(Map<String, num> json) : x = json['x'], y = json['y'] {
    print('In Point.fromJson(): ($x, $y)'); 
}
like image 19
binithb Avatar answered Nov 18 '22 20:11

binithb