问题
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