Code will explain all:
//modal for list
class MyModal
{
int myField1;
List adjacentNodes;
MyModal(this.myField1)
{
adjacentNodes= new Lis
List<T>.addall(T) worked for me
i.e.
List<mylist>.addall(oldlist)
class MyModal {
int myField1;
String myField2;
List<MyModal> adjacentNodes;
MyModal(this.myField1,this.myField2);
MyModal.clone(MyModal source) :
this.myField1 = source.myField1,
this.myField2 = source.myField2,
this.adjacentNodes = source.adjacentNodes.map((item) => new MyModal.clone(item)).toList();
}
var secondList = originalList.map((item) => new MyModal.clone(item)).toList();
If a member of MyModal
is of a non-primitive type like String
, int
, double
, num
, bool
, then the clone()
method needs to clone the instances references point to as well.
I think for your use case using immutable values is a better approach, for example with https://pub.dartlang.org/packages/built_value
Change it to JSON then parse it again to object. I know it's dirty way.
(+) it works and less code. (-) it not parsing method.
Recommended way is to use List.of()
constructor.
List<int> source = [1];
List<int> copied = List.of(source);
I just used thelist2 = thelist1.toList();
and it work
you can use List.from() function. try this code:
//modal for list
class MyModal {
int myField1;
String name;
List<MyModal> adjacentNodes;
MyModal(this.myField1, this.name) {
adjacentNodes = new List<MyModal>();
}
}
void runCopy() {
//pre code
List<MyModal> originalList = new List<MyModal>();
originalList.add(new MyModal(1, "firstBuddy"));
//copying list
List<MyModal> secondList = List.from(originalList);
secondList.addAll(originalList);
print(originalList);
print(secondList);
}