insertItems method

void insertItems(
  1. List<T> items,
  2. List<int> indices
)

Inserts the given items into the given indices.

items and indices should have the same number of items

All values in indices should be valid, which is to say that a given index shouldn't exceed the the number of items when all but 1 have been inserted. This method assumes that both lists are ordered in the way that you want the items to be inserted

Implementation

void insertItems(List<T> items, List<int> indices) {
  assert(items.length == indices.length);

  // validates the indices
  int maxNumItems = _items.length + indices.length;
  for (int index in indices) {
    if (index > maxNumItems) {
      throw Exception(
        "Index $index is invalid and can't be inserted into the list",
      );
    }
  }

  // If this is our initial insertion, and we're expanding on that, then we'll
  // put ourselves into the expanded state
  if (_expandOnInitialInsertion && _items.isEmpty) {
    value = ExpandableSliverListStatus.expanded;
  }

  _timer?.cancel();

  Duration period = Duration(milliseconds: (250 / items.length).round());

  _timer = Timer.periodic(
    period,
    (timer) {
      if (items.isNotEmpty && indices.isNotEmpty) {
        T item = items.removeAt(0);
        int index = indices.removeAt(0);

        // Otherwise, we'll insert it into our collection, and if we're not
        // collapsed, also animate it in
        _items.insert(index, item);

        if (!isCollapsed()) {
          listKey.currentState?.insertItem(index, duration: period);
          _numItemsDisplayed++;
        }
      }

      // Once we run out of items to add, we'll stop the timer and recalculate
      // our item period
      else {
        timer.cancel();
        _calcItemPeriod();
      }
    },
  );
}