dart - Flutter:构造函数中List参数的默认赋值

标签 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

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

最佳答案

默认值目前需要是常量。这在未来可能会改变。

如果你的默认值可以是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/

相关文章:

dart - 错误 : Only static members can be accessed in initializers what does this mean?

dart - 如何在我的 flutter 应用程序中打开一个应用程序而不让它填满整个屏幕?

flutter - 如何从Firestore文档的一个字段中获取数据?

ios - Flutter Spinkit 进度指示器

在堆栈中的另一个小部件下 flutter 混合/ mask 多个小部件

android-studio - Android Studio 在首选项中添加 flutter sdk 路径

flutter - 常量创建的参数必须是Flutter上的常量表达式

android - flutter 多指按下事件

Flutter:按下按钮时只能在初始化程序中访问静态成员

google-app-engine - 使用Dart在数据存储区中按键查询