对于带有 Named 或 Positional 参数的构造函数,我们可以使用 = 来定义默认值。
默认值必须是编译时常量。如果我们不提供值,则默认值为 null。
位置可选参数
class Customer {
String name;
int age;
String location;
Customer(this.name, [this.age, this.location = "US"]);
@override
String toString() {
return "Customer [name=${this.name},age=${this.age},location=${this.location}]";
}
}
现在创建一些Customer 对象,您可以看到age 的默认值为null,location 的默认值为"US"。
var customer = Customer("bezkoder", 26, "US");
print(customer);
// Customer [name=bezkoder,age=26,location=US]
var customer1 = Customer("bezkoder", 26);
print(customer1);
// Customer [name=bezkoder,age=26,location=US]
var customer2 = Customer("zkoder");
print(customer2);
// Customer [name=zkoder,age=null,location=US]
命名的可选参数
class Customer {
String name;
int age;
String location;
Customer(this.name, {this.age, this.location = "US"});
@override
String toString() {
return "Customer [name=${this.name},age=${this.age},location=${this.location}]";
}
}
让我们运行检查age 和location 的默认值。
var customer = Customer("bezkoder", age: 26, location: "US");
print(customer);
// Customer [name=bezkoder,age=26,location=US]
var customer1 = Customer("bezkoder", age: 26);
print(customer1);
// Customer [name=bezkoder,age=26,location=US]
var customer2 = Customer("zkoder");
print(customer2);
// Customer [name=zkoder,age=null,location=US]
常量构造函数
如果我们希望我们类的所有实例永远不会改变,我们可以定义一个 const 构造函数,其中所有字段都是final
class ImmutableCustomer {
final String name;
final int age;
final String location;
// Constant constructor
const ImmutableCustomer(this.name, this.age, this.location);
}
现在我们可以将const关键字放在构造函数名称之前:
var immutableCustomer = const ImmutableCustomer("zkoder", 26, "US");
// immutableCustomer.name = ... // compile error
参考:Constructor default value