How to initialize List/Map as a default argument?

允我心安 提交于 2020-08-09 09:10:38

问题


I know how to initialize other variables such as int or String in constructor but I have no clue how to do it for List and Map.

class StackOverFlowQuestion{
StackOverFlowQuestion({this.test='', this.map=?, this.list=?});
String test;
Map map;
List list;
}

What shall I replace the question marks with?

Thanks.


回答1:


The answer depends on whether your default list and map are constant. Let's assume your list is, but map is not.

You'd write:

class StackOverFlowQuestion {
  StackOverFlowQuestion({
    this.test = '',
    Map map,
    this.list = const [1, 2, 3],
  }) {
    this.map = map ?? {};
  }

  String test;
  Map map;
  List list;
}

If the list optional parameter is omitted, then it will be initialized to [1, 2, 3]. If the map is omitted or null, it will be initialized with a mutable empty map.



来源:https://stackoverflow.com/questions/62418736/how-to-initialize-list-map-as-a-default-argument

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