flutter - 从对象列表创建副本并更改新列表,而不更改原始的一个 flutter

标签 flutter dart

我有一个对象列表,我想获得该对象的副本并在不更改原始对象的情况下更改新对象。

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();

reference link

关于flutter - 从对象列表创建副本并更改新列表,而不更改原始的一个 flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63828719/

相关文章:

arrays - 使用flutter从Firestore获取用户数组数据

dart - 安装后,Flutter 发布的应用程序无法在设备上运行

flutter - 如何为到达页面后的窗口小部件树中的所有窗口小部件提供身份验证证书,并使导航器仍在工作

firebase - 在 null 上调用了方法 'add'

android - 在flutter中的android中实现face id

dart - 如何在 Dart 中使用 char 类型? (打印字母表)

android - 如何实现滑动删除 ListView 以从 firestore 中删除数据

flutter - flutter中认证成功后如何重定向到下一页

flutter - JSON 文件未在 Flutter 上加载

dart - 是否可以在某处以交互方式运行Dart代码?