replaceRange method

  1. @override
void replaceRange(
  1. int start,
  2. int end,
  3. Iterable<E> replacement, {
  4. bool notifyListeners = true,
})
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'

Note: Because this method removes the original elements then inserts the replacements, rather than a CollectionEventType.update being triggered, 2 events will be triggered, first a CollectionEventType.removal event, then a CollectionEventType.addition event.

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

@override
void replaceRange(
  int start,
  int end,
  Iterable<E> replacement, {
  bool notifyListeners = true,
}) {
  assert(start >= 0 && start <= length);
  assert(end >= start && end <= length);
  assert(replacement.length >= end - start);
  final elements = notifyListeners ? _toList(start, end) : null;
  value.replaceRange(start, end, replacement);
  if (notifyListeners) {
    if (elements != null) {
      _notifyEventListeners(CollectionEventType.removal, elements, start);
      _notifyEventListeners(CollectionEventType.addition, replacement, start);
    }
    this.notifyListeners(value);
  }
}