问题
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:
This is the intended behaviour and null the default if not given a value according to this.
回答1:
Edit: use the intializer:
class MyListClass {
List myList;
MyListClass({List list}) : myList = list ?? [];
}
来源:https://stackoverflow.com/questions/61303278/list-as-optional-constructor-parameter-is-null-in-dart