replaceRange method Null safety

void replaceRange (
  1. int start,
  2. int end,
  3. Iterable<E> newContents
)
override

Removes the objects in the range start inclusive to end exclusive and inserts the contents of replacement in its place.

List<int> list = [1, 2, 3, 4, 5];
list.replaceRange(1, 4, [6, 7]);
list.join(', '); // '1, 6, 7, 5'

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 <= start <= end <= len, where len is this list's length. The range starts at start and has length end - start. An empty range (with end == start) is valid.

This method does not work on fixed-length lists, even when replacement has the same number of elements as the replaced range. In that case use setRange instead.

Implementation

void replaceRange(int start, int end, Iterable<E> newContents) {
  RangeError.checkValidRange(start, end, this.length);
  if (start == this.length) {
    addAll(newContents);
    return;
  }
  if (newContents is! EfficientLengthIterable) {
    newContents = newContents.toList();
  }
  int removeLength = end - start;
  int insertLength = newContents.length;
  if (removeLength >= insertLength) {
    int insertEnd = start + insertLength;
    this.setRange(start, insertEnd, newContents);
    if (removeLength > insertLength) {
      _closeGap(insertEnd, end);
    }
  } else if (end == this.length) {
    int i = start;
    for (E element in newContents) {
      if (i < end) {
        this[i] = element;
      } else {
        add(element);
      }
      i++;
    }
  } else {
    int delta = insertLength - removeLength;
    int oldLength = this.length;
    int insertEnd = start + insertLength; // aka. end + delta.
    for (int i = oldLength - delta; i < oldLength; ++i) {
      add(this[i > 0 ? i : 0]);
    }
    if (insertEnd < oldLength) {
      this.setRange(insertEnd, oldLength, this, end);
    }
    this.setRange(start, insertEnd, newContents);
  }
}