in https://dartpad.dartlang.org/ https://dartpad.dartlang.org/编辑器我在下面输入来测试我的问题。
根据我的测试,显然 list.from 函数仅在 T 不是对象/类时创建一个新副本
我测试了 list.from 的 List ,它的工作方式类似于魅力,但不是类/对象。
请让我知道如何在下面的代码中创建 T 列表的新副本,以便当我们在一个地方更改列表时,其他地方不会发生更改。
thanks
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)