BeHappy
BeHappy

Reputation: 3988

Create copy from list of object and change new list without changing original one flutter

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?

Upvotes: 2

Views: 2504

Answers (3)

Harish Sharma
Harish Sharma

Reputation: 1549

You can try toJson and fromJson, i was also facing same problem, a list which has isSelected for change radio value. I have to show this list in carousel slider so if i change index 1 list, other indexes list also got change i try everything List.from, List.unmodifiable, List.of, List.addAll and all other options only toJson and fromJson works.

ReturnReason returnReasons = await ApiProvider().getReturnReason();
ReturnReason rList = ReturnReason.fromJson(returnReasons.toJson());

My ReturnReason class is-

import 'dart:convert';

ReturnReason returnReasonFromJson(String str) => ReturnReason.fromJson(json.decode(str));

String returnReasonToJson(ReturnReason data) => json.encode(data.toJson());

class ReturnReason {
  ReturnReason({
    this.status,
    this.message,
    this.data,
  });

  int status;
  String message;
  Data data;

  factory ReturnReason.fromJson(Map<String, dynamic> json) => ReturnReason(
    status: json["status"] == null ? null : json["status"],
    message: json["message"] == null ? null : json["message"],
    data: json["data"] == null ? null : Data.fromJson(json["data"]),
  );

  Map<String, dynamic> toJson() => {
    "status": status == null ? null : status,
    "message": message == null ? null : message,
    "data": data == null ? null : data.toJson(),
  };
}

class Data {
  Data({
    this.returnReason,
  });

  List<Reason> returnReason;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
    returnReason: json["return_reason"] == null ? null : List<Reason>.from(json["return_reason"].map((x) => Reason.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "return_reason": returnReason == null ? null : List<dynamic>.from(returnReason.map((x) => x.toJson())),
  };
}

class Reason {
  Reason({
    this.name,
    this.value,
    this.isSelected,
  });

  String name;
  String value;
  bool isSelected;

  factory Reason.fromJson(Map<String, dynamic> json) => Reason(
    name: json["name"] == null ? null : json["name"],
    value: json["value"] == null ? null : json["value"],
    isSelected: false
  );

  Map<String, dynamic> toJson() => {
    "name": name == null ? null : name,
    "value": value == null ? null : value,
    "isSelected": isSelected
  };
}

Upvotes: 1

BeHappy
BeHappy

Reputation: 3988

I found this solution and works:

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

and get copy with this:

var comments = incomingComments.map((e) => Comment.clone(e)).toList();

reference link

Upvotes: 2

Yilmaz Guleryuz
Yilmaz Guleryuz

Reputation: 9745

you can try replacing
var comments = List.from(incomingComments);

with
List comments = List()..addAll(incomingComments)

and instead of List<Comment> finalArr = []; please use List<Comment> finalArr = List();

Upvotes: -1

Related Questions