Created
October 17, 2021 17:27
-
-
Save FantasyCheese/2e84adf910a219de6d923f07d7e7b4dd to your computer and use it in GitHub Desktop.
Copy data class with recursive children
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
Node(this.title, [this.children = const []]); | |
final String title; | |
final List<Node> children; | |
} | |
Node copy(Node n) { | |
// create new object with data from old object | |
return Node( | |
n.title, | |
// for each child map with copy recursively to create new list of children | |
n.children.map(copy).toList(), | |
); | |
} | |
main() { | |
final oldList = [ | |
Node('A', [Node('B'), Node('C')]), | |
Node('D', [ | |
Node('E', [Node('F')]) | |
]), | |
]; | |
final newList = oldList.map(copy).toList(); | |
oldList[1].children[0].children.clear(); | |
print(oldList[1].children[0].children); | |
print(newList[1].children[0].children); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment