separate<E> function

  1. @useResult
List<E> separate<E>(
  1. List<E> list, {
  2. required List<E> by,
})

Returns a copy of the list with its elements separated by those in by.

final original = [ Fi(), Fo(), Fum() ];
final list = separate(original, by: [ A(), B() ]);

print(list); // [ Fi(), A(), B(), Fo(), A(), B(), Fum() ]

Implementation

@useResult List<E> separate<E>(List<E> list, {required List<E> by}) {
  // No errors are thrown if [list] or [by] is empty as it is extremely disruptive to prototyping UIs in Flutter.
  final result = <E>[];
  for (var i = 0; i < list.length; i++) {
    result.add(list[i]);
    if (i < list.length - 1) {
      result.addAll(by);
    }
  }

  return result;
}