I have a list of object and I want to have copy of that and change new one without changing original one.
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;
}
Comment class:
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'];
}
I try this, but it change original list, too.
How can I achieve that?