Flutter:构造函数中List参数的默认分配 [英] Flutter: Default assignment of List parameter in a constructor

查看:773
本文介绍了Flutter:构造函数中List参数的默认分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to assign a constant value to an optional parameter of datatype List while defining a constructor. for example,

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

上面的代码抛出了一个针对y赋值的错误,称可选参数的默认值必须是恒定的

the above code throws an error focused at y assignment saying Default values of an optional parameter must be constant

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

what is the reason for this error? how else can I assign a default value to the List?

推荐答案

当前默认值必须为const。

Default values currently need to be const. This might change in the future.

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

If your default value can be const, adding const would be enough

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

Dart通常只假设 const 当需要 const 时,但是对于默认值,如果在实际删除约束的情况下忽略了它,不会破坏现有代码。

Dart usually just assumes const when const is required, but for default values this was omitted to not break existing code in case the constraint is actually removed.

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

If you want a default value that can't be const because it's calculated at runtime you can set it in the initializer list

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

这篇关于Flutter:构造函数中List参数的默认分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆