Flutter:构造函数中List参数的默认分配

时间:2019-01-20 17:49:38

标签: dart flutter

是否可以在定义构造函数时将常量值分配给数据类型为List的可选参数。 例如,

`class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0; this.y = ["y","y","y","y"]});
 }`

上面的代码抛出了一个错误,该错误集中在y赋值上,Default values of an optional parameter must be constant

此错误的原因是什么? 我还能如何为列表分配默认值?

2 个答案:

答案 0 :(得分:3)

当前默认值必须为const。将来可能会改变。

如果您的默认值可以是const,那么添加const就足够了

class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0; this.y = const ["y","y","y","y"]});
}

在需要使用const时,Dart通常只假设const,但是对于默认值,在实际删除约束的情况下,为了避免破坏现有代码,将其省略。

如果您想要一个默认值,因为它是在运行时计算的,则不能为const,则可以在初始值设定项列表中进行设置

class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0; List<String> y}) : y = y ?? ["y","y","y","y"];
}

答案 1 :(得分:1)

对于具有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的默认值为nulllocation的默认值为"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}]";
  }
}

让我们检查agelocation的默认值。

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

Ref:Constructor default value

相关问题