在定义构造函数时,是否可以将常量值分配给数据类型为 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
这个错误的原因是什么? 我还能如何为列表分配默认值?
最佳答案
默认值目前需要是常量。这在未来可能会改变。
如果你的默认值可以是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
,但对于默认值,这被省略了,以防在实际删除约束的情况下不破坏现有代码。
如果你想要一个不能是常量的默认值,因为它是在运行时计算的,你可以在初始化列表中设置它
class sample{
final int x;
final List<String> y;
sample({this.x = 0; List<String> y}) : y = y ?? ["y","y","y","y"];
}
关于dart - Flutter:构造函数中List参数的默认赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279223/