listEquals<T> function

bool listEquals<T>(
  1. List<T> list1,
  2. List<T> list2, {
  3. bool equalityCheck(
    1. T a,
    2. T b
    )?,
})

Check if a list of items is equal to another list of items. Lists are considered equal if they have the same number of values and each of those values are equal. A custom equalityCheck can be provided for objects that don't override their equality operator or need to be deemed equal based on varying application logic.

Implementation

bool listEquals<T>(List<T> list1, List<T> list2,
    {bool Function(T a, T b)? equalityCheck}) {
  if (identical(list1, list2)) return true;
  int length = list1.length;
  if (length != list2.length) return false;
  // A little more verbose to wrap the loop with the conditional but more
  // efficient at runtime.
  if (equalityCheck != null) {
    for (int i = 0; i < length; i++) {
      if (!equalityCheck(list1[i], list2[i])) {
        return false;
      }
    }
  } else {
    for (int i = 0; i < length; i++) {
      if (list1[i] != list2[i]) {
        return false;
      }
    }
  }
  return true;
}