replaceChild function

Future<void> replaceChild(
  1. WidgetModel model,
  2. List arguments
)

Implementation

Future<void> replaceChild(WidgetModel model, List<dynamic> arguments) async {
  // fml
  var xml = elementAt(arguments, 0);

  // if index is null, remove last child before replacement.
  int? index = toInt(elementAt(arguments, 1));

  // silent
  bool silent = toBool(elementAt(arguments, 2)) ?? true;

  if (xml == null || xml is! String) return;

  // check for children then remove them
  if (model.children != null && index == null) {
    // dispose of the last item
    model.children!.last.dispose();

    // check if the list is greater than 0, remove at the final index.
    if (model.children!.isNotEmpty) {
      model.children!.removeAt(model.children!.length - 1);
    }
  } else if (model.children != null && index != null) {
    // check if index is in range, then dispose of the child at that index.
    if (index >= 0 && model.children!.length > index) {
      model.children![index].dispose();
      model.children!.removeAt(index);
    }
    // Could add handling for negative index removing from the end?
  }

  // add elements
  await _appendXml(model, xml, index, silent);
}