0

The question by @george koller linked below asks the same question I'm asking, which is: "What is the best way to deep copy an object in Dart?" How can I clone an Object (deep copy) in Dart? The answers are helpful, but I had a hard time since most of the answers point to a way to shallow copy a list. In my particular case, I wanted to make a deep copy of a List<List<int>> and had tried using the [...List] method already, with no luck. using json to encode and decode the list technically did work but very slowly and unfortunately lost the class type in the process. It looks like there is not any language supported method to deep copy a list in Dart, so what can I do to deep copy a list?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
lwhitena
  • 21
  • 5

1 Answers1

0

The medium article https://suragch.medium.com/cloning-lists-maps-and-sets-in-dart-d0fc3d6a570a answers this question very clearly and also explains why Dart doesn't have any language-supported methods. The method used in the article to deep copy a List<List<int>> is as such:

List<List<int>> deepCopy(List<List<int>> source) {
  return source.map((e) => e.toList()).toList();
}

But the best solution is to use immutable objects whenever possible.

lwhitena
  • 21
  • 5