我有一个对象列表,我想获得该对象的副本并在不更改原始对象的情况下更改新对象。
List<Comment> manageComment(List<Comment> incomingComments) {
List<Comment> finalArr = [];
var comments = List.from(incomingComments);
while (comments.isNotEmpty) {
var comment = comments.removeAt(0);
if (comment.parentId == null) {
finalArr.add(comment);
} else {
for (var i = 0; i < finalArr.length; i++) {
var el = finalArr[i];
if (el.commentId == comment.parentId) {
comment.replyTo = el.user;
el.children.add(comment);
break;
} else {
for (var j = 0; j < el.children.length; j++) {
var childEl = el.children[j];
if (childEl.commentId == comment.parentId) {
comment.replyTo = childEl.user;
el.children.add(comment);
break;
}
}
}
}
}
}
print(finalArr[0].children);
return finalArr;
}
评论类:
class Comment {
String commentId;
User user;
User replyTo;
String text;
num date;
String parentId;
List<Comment> children;
Comment({
this.commentId,
this.user,
this.replyTo,
this.text,
this.date,
this.parentId,
this.children,
});
Comment copyWith({
String commentId,
User user,
User replyTo,
String text,
num date,
String parentId,
List<Comment> children,
}) {
return Comment(
commentId: commentId ?? this.commentId,
user: user ?? this.user,
replyTo: replyTo ?? this.replyTo,
text: text ?? this.text,
date: date ?? this.date,
parentId: parentId ?? this.parentId,
children: children ?? this.children,
);
}
Comment.fromJson(Map json)
: commentId = json['commentId'],
text = json['text'],
parentId = json['parentId'],
user = User.fromJson(json['user']),
children = [],
date = json['date'];
}
我尝试了这个,但它也改变了原始列表。
我怎样才能实现这一目标?
最佳答案
我找到了这个解决方案并且有效:
在评论类(class)中:
Comment.clone(Comment source)
: this.commentId = source.commentId,
this.user = source.user,
this.replyTo = source.replyTo,
this.text = source.text,
this.date = source.date,
this.parentId = source.parentId,
this.children = source.children.map((item) => Comment.clone(item)).toList();
并获取副本:
var comments = incomingComments.map((e) => Comment.clone(e)).toList();
关于flutter - 从对象列表创建副本并更改新列表,而不更改原始的一个 flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63828719/