concat method

List<T> concat(
  1. List<T>? list2, [
  2. List<T>? list3,
  3. List<T>? list4,
  4. List<T>? list5,
])

Return an efficient concatenation of up to 5 lists:

list = list1.concat(list2, list3, list4, list5);

The resulting list has fixed size, but is not unmodifiable/immutable. Passing null is the same as passing empty lists (they will be ignored). You should only use this if you need to concatenate lists as efficient as possible, or if your lists may be null. Otherwise, just add the lists like this:

list = list1 + list2 + list3 + list4 + list5;

Implementation

List<T> concat(List<T>? list2, [List<T>? list3, List<T>? list4, List<T>? list5]) {
  List<T> list1 = this;
  list2 ??= const [];
  list3 ??= const [];
  list4 ??= const [];
  list5 ??= const [];

  var totalLength = list1.length + list2.length + list3.length + list4.length + list5.length;

  // Return a non-const list, so that it can be sorted.
  if (totalLength == 0) return [];

  T anyItem = list1.isNotEmpty
      ? list1.first
      : list2.isNotEmpty
          ? list2.first
          : list3.isNotEmpty
              ? list3.first
              : list4.isNotEmpty
                  ? list4.first
                  : list5.first;

  /// Preallocate the necessary number of items, and then copy directly into place.
  return List<T>.filled(totalLength, anyItem)
    ..setAll(0, list1)
    ..setAll(list1.length, list2)
    ..setAll(list1.length + list2.length, list3)
    ..setAll(list1.length + list2.length + list3.length, list4)
    ..setAll(list1.length + list2.length + list3.length + list4.length, list5);
}