dart - 当 T 是对象时,如何在 dart 中创建 List<T> 的副本,请参见下面的代码

标签 dart flutter

https://dartpad.dartlang.org/我在下面输入的编辑器来测试我的问题。

根据我的测试显然 list.from 函数只在 T 不是对象/类时创建一个新副本

我测试了 list.from 的 List,它像魅力一样工作,但不是类/对象。

请告诉我如何在下面的代码中创建 T 列表的新副本,这样当我们在一个地方更改列表时,另一个地方不会发生变化。

谢谢

void main() {
  List<Status> statuses = <Status>[
    Status(name: 'Confirmed', isCheck: true),
    Status(name: 'Cancelled', isCheck: true),
  ];
  print('statuses = ${statuses.toList().map((x) => x.name + '=' + x.isCheck.toString())}');

  //this supposed to create a new list of T but apparently only work for non-object
  List<Status> otherStatuses =  new List<Status>.from(statuses);

  print('otherStatuses= ${otherStatuses.toList().map((x) => x.name + '=' + x.isCheck.toString())}');

 otherStatuses.singleWhere((x)=>x.name=='Cancelled').isCheck=false;

  print('after the changes only on otherStatuses');
  print('statuses = ${statuses.toList().map((x) => x.name + '=' + x.isCheck.toString())}');

  print('statuses2 = ${otherStatuses.toList().map((x) => x.name + '=' + x.isCheck.toString())}');

  print('why the original status (cancelled) equal to false?');

}


class Status {
  String name;
  bool isCheck;

  Status({
    this.name,
    this.isCheck,
  });
}

最佳答案

要创建新元素列表,请使用您已在代码中用于其他目的的 map() 函数:

List<Status> otherStatuses = statuses.map((status)=>Status(name:status.name, isCheck:status.isCheck)).toList()

关于dart - 当 T 是对象时,如何在 dart 中创建 List<T> 的副本,请参见下面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54154230/

相关文章:

object - 如何在 Dart 中克​​隆对象(深拷贝)?

Dart - 静态类型列表中的值

json - 以 Map<String, dynamic> 作为正文的 Dart HTTP POST

dart - 声明必须是子类的Type变量-Dart

dart - 是否有可用的 Material 表?

dart - Flutter - 如何让带有 child 的容器占据整个屏幕

firebase - Firestore 事务失败,出现 "Transaction failed all retries"

flutter - 当我打印调试时,它显示 Flutter 中的 type-->Instance of 'Future<dynamic>'

android - Bad Request 400 从 Flutter 请求 ASP.Net Core 3.0

flutter - Flutter聊天应用程序可保存设备时间中的消息时间戳