dart 中的构造函数后的冒号 [英] 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));
特别是我会知道构造函数后面的冒号是什么意思,以及是否有办法定义另一个 TextEditingController,除了已经定义的那个.
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.
推荐答案
:
之后的部分称为初始化列表".它是一个 ,
分隔的表达式列表,可以访问构造函数参数并可以分配给实例字段,甚至是 final
实例字段.这对于使用计算值初始化最终字段非常方便.
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.
初始化列表还用于调用其他构造函数,如: ..., super('foo')
.
The initializer list is also used to call other constructors like : ..., super('foo')
.
从 Dart 1.24 版本开始,初始化器列表也支持 assert(...)
,它可以方便地检查参数值.
Since about Dart version 1.24 the initializer list also supports assert(...)
which is handy to check parameter values.
初始化列表不能从this
读取,因为在访问this
有效之前需要完成超级构造函数,但它可以赋值给this.xxx
.
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
.
如 user693336 在评论中提到的那样指出:
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.
示例(复制自 https://github.com/dart-lang/language/问题/1394):
class C {
final int x;
final int y;
C(this.x) : y = x + 1;
}
这篇关于dart 中的构造函数后的冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!