【问题标题】:dart how to assign list into a new list variable飞镖如何​​将列表分配给新的列表变量
【发布时间】:2019-08-22 14:22:15
【问题描述】:

我正在尝试通过使用 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);

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

【问题讨论】:

  • 您正在尝试将 add 的结果分配给一个新变量。 add() 更改现有列表。您可以将mylists 重新分配给d,但这会创建一个引用。如果你想要一份(又名保留旧的)看看here

标签: dart


【解决方案1】:

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'];

【讨论】:

    【解决方案2】:

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

    List 类的add 方法的返回类型为void
    所以你无法分配var d

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2012-01-05
      • 2020-09-29
      相关资源
      最近更新 更多