addSibling method

TreeNodeId addSibling(
  1. TreeNodeId id, {
  2. String label = 'New item',
  3. T? value,
})

Insert a sibling immediately after id (or append at root if id has no parent and isn't found nested). Returns the new node's id.

Implementation

TreeNodeId addSibling(TreeNodeId id, {String label = 'New item', T? value}) {
  final newId = _newId();
  final sibling = TreeNode<T>(id: newId, label: label, value: value);
  final ancestors = TreeOps.ancestorsOf<T>(_roots, id);
  if (ancestors.isEmpty) {
    // Root-level sibling.
    final out = <TreeNode<T>>[];
    for (final n in _roots) {
      out.add(n);
      if (n.id == id) out.add(sibling);
    }
    _apply(out);
  } else {
    _apply(TreeOps.insertAfter<T>(_roots, id, sibling));
  }
  _selected = newId;
  _focused = newId;
  _editing = newId;
  return newId;
}