Add items inbetween

Add items inbetween

Add items inbetween others in a list

This will add items inbetween items in a lists, e.g.:

['1','x','1','x','1','x','1','x','1']

Can be useful for adding spaces or seperators inbetween widgets.

extension IterableAddInBetween<T> on Iterable<T> {
  Iterable<T> addInBetween(
    T inBetweenElement,
  ) sync* {
    var index = 0;
    for (final element in this) {
      yield element;

      // Only adding if there is more that one and
      // it is not the last one
      if (length > 1 && index != length - 1) {
        yield inBetweenElement;
      }
      index++;
    }
  }
}

this extension can then be used like so:

import 'package:collection/collection.dart';

final items = ['1','1','1','1','1'];

void main() {  
  final itemsWith = items.addInBetween('x').toList();
  print(itemsWith);
}