简体   繁体   English

Dart:如何创建一个空列表作为默认参数

[英]Dart: how to create an empty list as a default parameter

I have multiple lists that need to be empty by default if nothing is assigned to them.如果没有分配任何内容,我有多个列表默认情况下需要为空。 But I get this error:但我得到这个错误:

class Example {
    List<String> myFirstList;
    List<String> mySecondList;

    Example({
        this.myFirstList = [];  // <-- Error: default value must be constant
        this.mySecondList = [];
    });
}

But then of course if I make it constant, I can't change it later:但是当然,如果我让它保持不变,我以后就不能改变它了:

Example({
    this.myFirstList = const [];
    this.mySecondList = const [];
});

...

Example().myFirstList.add("foo"); // <-- Error: Unsupported operation: add (because it's constant)

I found a way of doing it like this, but how can I do the same with multiple lists:我找到了一种这样做的方法,但是我怎样才能对多个列表做同样的事情:

class Example {
    List<String> myFirstList;
    List<String> mySecondList;

    Example({
        List<String> myFirstList;
        List<String> mySecondList;
    }) : myFirstList = myFirstList ?? []; // <-- How can I do this with multiple lists?
}

Like this像这样

class Example {
    List<String> myFirstList;
    List<String> mySecondList;

    Example({
        List<String> myFirstList,
        List<String> mySecondList,
    }) : myFirstList = myFirstList ?? [], 
         mySecondList = mySecondList ?? [];
}

Expanding on YoBo's answer (since I can't comment on it)扩展 YoBo 的答案(因为我无法对此发表评论)

Note that with null-safety enabled, you will have to add ?请注意,启用 null-safety 后,您必须添加? to the fields in the constructor, even if the class member is marked as non-null;到构造函数中的字段,即使 class 成员被标记为非空;

class Example {
List<String> myFirstList;
List<String> mySecondList;

Example({
    List<String>? myFirstList,
    List<String>? mySecondList,
}) : myFirstList = myFirstList ?? [], 
     mySecondList = mySecondList ?? [];
}

See in the constructor you mark the optional parameters as nullable (as not being specefied in the initialization defaults to null), then the null aware operator ??在构造函数中看到您将可选参数标记为可为空(在初始化默认为空时未指定),然后 null 感知运算符?? in the intitializer section can do it's thing and create an empty list if needed.在初始化程序部分可以做这件事并在需要时创建一个空列表。

class Example {
    List<String> myFirstList;
    List<String> mySecondList;

    Example({
        List<String> myFirstList,
        List<String> mySecondList,
    }) : myFirstList = myFirstList ?? [], 
         mySecondList = mySecondList ?? [];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM