考虑下面的代码:
class Person {
String id;
String name;
ConnectionFactory connectionFactory;
// What is this constructor doing?
Person({this.connectionFactory: _newDBConnection});
}
如果在构造函数的参数前面加上this
,相应的字段将自动初始化,但为什么是{...}
呢?
考虑下面的代码:
class Person {
String id;
String name;
ConnectionFactory connectionFactory;
// What is this constructor doing?
Person({this.connectionFactory: _newDBConnection});
}
如果在构造函数的参数前面加上this
,相应的字段将自动初始化,但为什么是{...}
呢?
这使该参数成为命名的可选参数.
当你实例化一个Person
,你可以
Person p;
p = new Person(); // default is _newDbConnection
p = new Person(connectionFactory: aConnectionFactoryInstance);
{}
,参数将是必需的[]
,该参数将是可选的位置参数 // Constructor with positional optional argument
Person([this.connectionFactory = _newDBconnection]);
...
Person p;
p = new Person(); // same as above
p = new Person(aConnectionFactoryInstance); // you don't specify the parameter name
命名的可选参数对于布尔参数非常方便(当然,对于其他情况也是如此).
p = new Person(isAlive: true, isAdult: false, hasCar: false);
这些参数类型的使用有一个特定的顺序:
请注意,位置和命名可选参数使用不同的分隔符作为默认值.
从DART 2开始支持=
作为分隔符,并且根据样式指南首选,同时仍然支持:
.
另请参阅: