[英]List as optional constructor parameter is null in Dart
In the following example, why is myList
null
when no parameter is passed to the constructor?在下面的例子中,当没有参数传递给构造函数时,为什么
myList
null
?
I declare it as an empty ( growable ) list in the class.我在 class 中将其声明为空(可增长)列表。
class MyListClass {
List myList = [];
MyListClass({this.myList});
}
void main() {
final obj = MyListClass();
assert(obj.myList != null);
}
What is the best way to pass an optional list, but default to an empty list?传递可选列表但默认为空列表的最佳方法是什么?
I know you can do the following, but maybe there is a better way?我知道您可以执行以下操作,但也许有更好的方法?
MyListClass({this.myList}) {
this.myList ??= [];
}
UDATE: This is the intended behaviour and null
the default if not given a value according to this . UDATE:这是预期的行为,
null
如果未根据此给出值,则为默认值。
Edit: use the intializer:编辑:使用初始化器:
class MyListClass {
List myList;
MyListClass({List list}) : myList = list ?? [];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.