如何将列表/映射初始化为默认参数? [英] How to initialize List/Map as a default argument?

查看:60
本文介绍了如何将列表/映射初始化为默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在构造函数中初始化其他变量,例如int或String,但我不知道如何对List和Map进行初始化。

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;
}

我用什么代替问号?

谢谢。

推荐答案

答案取决于您的默认列表和映射是否恒定。假设您的列表是列表,但地图不是。

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

您会这样写:

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

  String test;
  Map map;
  List list;
}

如果省略了list可选参数,则它将初始化为 [1、2、3] 。如果地图被省略或为null,则会使用可变的空地图进行初始化。

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.

这篇关于如何将列表/映射初始化为默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆