dart如何将列表分配到新的列表变量中

时间:2019-04-01 12:08:01

标签: dart

我正试图仅使用add这样的方法来扩展列表

List<String> mylists = ['a', 'b', 'c'];
var d = mylists.add('d');
print(d);

它给出了错误 This expression has type 'void' and can't be used. print(d);

为什么我不能将列表保存在新变量中?谢谢

2 个答案:

答案 0 :(得分:2)

mylists.add('d')会将参数添加到原始列表中。

如果要创建新列表,则有以下几种可能性:

List<String> mylists = ['a', 'b', 'c'];

// with the constructor
var l1 = List.from(mylists);
l1.add('d');

// with .toList()
var l2 = mylists.toList();
l2.add('d');

// with cascade as one liner
var l3 = List.from(mylists)..add('d');
var l4 = mylists.toList()..add('d');

// in a upcoming version of dart with spread (not yet available)
var l5 = [...myList, 'd'];

答案 1 :(得分:1)

引用Dart文档:https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html

add类的List方法的返回类型为void
因此,您无法分配var d

要将列表保存在新变量中,请使用:

List<String> mylists = ['a', 'b', 'c'];
mylists.add('d');
var d = mylists;
print(d);

首先添加新的字符串,即'd'
然后将其分配给新变量

相关问题