replaceRange method

  1. @override
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.

Implementation

@override
void replaceRange(int start, int end, Iterable<E> newContents) {
  assert(0 <= start && start <= end && end <= length);
  var i = start;
  for (var elem in newContents) if (i < end) this[i++] = elem;
  if (end - start < newContents.length)
    for (var elem in newContents.skip(end - start)) insert(i++, elem);
  if (end - start > newContents.length)
    removeRange(end - newContents.length, end);
}