Skip to content

Instantly share code, notes, and snippets.

@FantasyCheese
Created October 17, 2021 17:27
Show Gist options
  • Save FantasyCheese/2e84adf910a219de6d923f07d7e7b4dd to your computer and use it in GitHub Desktop.
Save FantasyCheese/2e84adf910a219de6d923f07d7e7b4dd to your computer and use it in GitHub Desktop.
Copy data class with recursive children
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