List as optional constructor parameter is null in Dart

旧时模样 提交于 2020-04-30 08:45:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!