To deep copy a list in Dart, you can use the `map` method to iterate through the list and create a new list with cloned elements.
In this example,
originalList
with integer values.map
method of originalList
to iterate through each element and create a new list with the same elements.toList
method converts the iterable result of map
back to a list.void main() {
List<int> originalList = [1, 2, 3, 4, 5];
List<int> deepCopiedList = originalList.map((element) => element).toList();
print('Original List: \$originalList');
print('Deep Copied List: \$deepCopiedList');
}
Original List: [1, 2, 3, 4, 5] Deep Copied List: [1, 2, 3, 4, 5]
In this example,
Person
with properties name
and age
.originalList
containing Person
objects.map
method to iterate through each Person
object and create a new Person
object with the same properties.toList
method converts the iterable result of map
back to a list.class Person {
String name;
int age;
Person(this.name, this.age);
Person clone() => Person(this.name, this.age);
@override
String toString() => 'Person(name: \$name, age: \$age)';
}
void main() {
List<Person> originalList = [
Person('Alice', 30),
Person('Bob', 25),
Person('Charlie', 35)
];
List<Person> deepCopiedList = originalList.map((person) => person.clone()).toList();
print('Original List: \$originalList');
print('Deep Copied List: \$deepCopiedList');
}
Original List: [Person(name: Alice, age: 30), Person(name: Bob, age: 25), Person(name: Charlie, age: 35)] Deep Copied List: [Person(name: Alice, age: 30), Person(name: Bob, age: 25), Person(name: Charlie, age: 35)]
In this tutorial, we learned How to deep Copy a List in Dart language with well detailed examples.