renggli/dart-more

Iterable<T> insertBetween(T element) on Iterable<T>

Closed this issue · 3 comments

Hey guys, I made this:

extension InsertBetweenExtension<T> on Iterable<T> {
  Iterable<T> insertBetween(T element) {
    final result = expand(
      (item) => [
        item,
        element,
      ],
    );

    return result.take(result.length - 1);
  }
}

It is useful in Flutter to insert dividers or paddings between widgets when you can't use the ListView.separated constructor (Row, Column, SliverList, etc.).

Row(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: products
    .map<Widget>(
      (id) => Expanded(
        child: id != null ? ProductTile(id: id) : SizedBox.shrink(),
      ),
    )
    .insertBetween(SizedBox(width: 8.0))
    .toList(),
) 

Can it be an interesting addition to this package?

Definitely a very interesting addition. In fact, I was planning to add something along these lines.

One thing I am wondering is if insertBetween shouldn't take a builder function as the argument, instead of a constant? Does this work in your example, if the same SizedBox is reused multiple times?

What do you think about 3520472?

Sounds great, thank you!