在Dart中作为可选构造函数参数列出的null为null [英] List as optional constructor parameter is null in Dart
本文介绍了在Dart中作为可选构造函数参数列出的null为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,为什么没有参数传递给构造函数时为何myList
null
?
In the following example, why is myList
null
when no parameter is passed to the constructor?
我在类中将其声明为空(可增长)列表.
I declare it as an empty ( growable ) list in the 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: 这是预期的行为,如果没有根据null为默认值. >此.
UDATE:
This is the intended behaviour and null
the default if not given a value according to this.
推荐答案
编辑:使用初始化器:
class MyListClass {
List myList;
MyListClass({List list}) : myList = list ?? [];
}
这篇关于在Dart中作为可选构造函数参数列出的null为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文