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 .
Edit: use the intializer:
class MyListClass {
List myList;
MyListClass({List list}) : myList = list ?? [];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.