在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/