在 Dart 中返回 [...list] 有什么用?

What is the use of returning [...list] in Dart?

在 Dart 编程语言中,有时我会看到函数 return 在带有三个点 [...list] 的一对括号中列出一个列表。例如:

class IntList {
    List<int> _integerList = [1, 2, 3, 4, 5];
    List<int> get integerList {
        return [..._integerList];
    }
}

那么return integerList;和上面的return语句有什么区别呢?

非常感谢任何帮助。谢谢。

对于这个特殊情况,没有区别。 ... 是传播运算符。这允许您将多个元素插入到集合中。

例如:

var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2)

Output:
[0, 1, 2, 3]

这样做 return [..._integerList]; 与 return integerList; 完全相同,除了它会创建一个新列表。


var list = [1, 2, 3];
print(list.hashCode);
print([...list].hashCode);

这段代码表明,由于散列码的输出不同,所以使用展开运算符时,它们是不同的 List个对象。