在DART中将列表的值实际复制到另一个列表的方法

在DART中将列表的值实际复制到另一个列表的方法,dart,Dart,经过研究,我了解到当一个列表设置了另一个列表中的值时,只会复制引用,而不会复制实际值 最初,我想创建一个列表,其中包含原始列表值的精确副本。然后,在对原始列表执行一些操作后,我希望能够将值从复制列表复制回原始列表 到目前为止,我找不到一个解决方案,它不会将复制列表中的值设置为与原始列表中的新值相同 下面的代码显示了我想要执行的逻辑,但是找不到能够创建克隆列表的正确函数 class NumPairs { NumPairs({this.first, this.second}); int fi

经过研究,我了解到当一个列表设置了另一个列表中的值时,只会复制引用,而不会复制实际值

最初,我想创建一个列表,其中包含原始列表值的精确副本。然后,在对原始列表执行一些操作后,我希望能够将值从复制列表复制回原始列表

到目前为止,我找不到一个解决方案,它不会将复制列表中的值设置为与原始列表中的新值相同

下面的代码显示了我想要执行的逻辑,但是找不到能够创建克隆列表的正确函数

class NumPairs {
  NumPairs({this.first, this.second});
  int first;
  int second;
}

main() {
  List<NumPairs> from = [
    NumPairs(
      first: 1,
      second: 2,
    ),
    NumPairs(
      first: 2,
      second: 1,
    ),
  ];

  List<NumPairs> to = [];

  to = from;

  print('${to[0].first} ' + '${to[0].second} ' + ' inital TO');
  print('${from[0].first} ' + '${from[0].second} ' + ' inital FROM');

  to[0].first = 0;
  to[0].second = 0;

  print('${to[0].first} ' + '${to[0].second} ' + ' after zeroed TO = 0');
  print(
      '${from[0].first} ' + '${from[0].second} ' + ' FROM after TO is zeroed');

  to = from;

  print('${to[0].first} ' +
      '${to[0].second} ' +
      ' after trying to copy to from FROM');
}

听起来您希望能够克隆原始列表中的对象。这可以按如下方式进行

class NumPairs {
    NumPairs({this.first, this.second});
    int first;
    int second;
    NumPairs.clone(NumPairs numpairs): this(first: numpairs.first, second: numpairs.second);
}
其中添加了命名构造函数“clone”

现在,您可以使用以下方法克隆原始列表:

List<NumPairs> to = from.map((elem)=>NumPairs.clone(elem)).toList();

我不知道你想要什么样的行为。你能写出你想要的输出吗?如果要克隆,只需从现有列表创建一个新列表即可。如果需要一个新列表,其中每个元素都是另一个列表中元素的副本,则可以使用map方法遍历旧列表并复制每个元素。但我不确定你在找什么,所以我不能给出详细的答案。这太好了。谢谢在发布问题之前,我找到了一些类似的解决方案,但我无法理解这部分代码:from.mapelem=>NumPairs.cloneelem.toList;
List<NumPairs> to = from.map((elem)=>NumPairs.clone(elem)).toList();
class NumPairs {
  NumPairs({this.first, this.second});
  int first;
  int second;
  NumPairs.clone(NumPairs numpairs): this(first: numpairs.first, second: numpairs.second);
}

main() {
  List<NumPairs> from = [
    NumPairs(
      first: 1,
      second: 2,
    ),
    NumPairs(
      first: 2,
      second: 1,
    ),
  ];

  //to = from;
  // Gets replaced with the following which clones the 'from' list
  List<NumPairs> to = from.map((elem)=>NumPairs.clone(elem)).toList();


  print('${to[0].first} ' + '${to[0].second} ' + ' inital TO');
  print('${from[0].first} ' + '${from[0].second} ' + ' inital FROM');

  to[0].first = 0;
  to[0].second = 0;

  print('${to[0].first} ' + '${to[0].second} ' + ' after zeroed TO = 0');
  print(
      '${from[0].first} ' + '${from[0].second} ' + ' FROM after TO is zeroed');

  to = from;

  print('${to[0].first} ' +
      '${to[0].second} ' +
      ' after trying to copy to from FROM');
}
1 2  inital TO
1 2  inital FROM
0 0  after zeroed TO = 0
1 2  FROM after TO is zeroed
1 2  after trying to copy to from FROM