Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add alternateWith extension method on Iterable #227

Open
alexeyinkin opened this issue Dec 21, 2021 · 1 comment
Open

Add alternateWith extension method on Iterable #227

alexeyinkin opened this issue Dec 21, 2021 · 1 comment

Comments

@alexeyinkin
Copy link

There is a repeating feature request in Flutter to add separators for children of Row and Column:
flutter/flutter#16957
flutter/flutter#18917
flutter/flutter#55378
flutter/flutter#95263
flutter/flutter#95521

At its highest it got 117 thumbs-ups.
But it is declined over and over again because it can be solved outside of the framework with a few lines of code:

Iterable<T> alternateWith(Iterable<T> items, T separator) {
  return items
      .expand((item) sync* { yield separator; yield item; })
      .skip(1);
}

Can we add it to this package as an extension on Iterable? One could then do:

Column(
  children: <Widget>[
    Widget1(),
    Widget2(),
  ].alternateWith(separator).toList(),
),

One could easily make another package with this, as there are many. Yet they are unknown and may be poorly maintained. This package is widely used, endorsed, and can be referred to in Flutter docs thus ending the recurrance of the feature request or speeding up the debate should it occur again.

I can do it myself if approved.

@lrhn
Copy link
Member

lrhn commented Sep 9, 2022

This is equivalent to dart-lang/sdk#49900.

The biggest problem is the typing. We can create an extension method like:

extension X<T> on Iterable<T> {
  Iterable<T> intersperse(T separator, {bool beforeFirst = false, bool afterLast = false}) sync* {
    bool empty = true;
    for (var e in this) {
      if (!empty || beforeFirst) yield separator;
      empty = false;
      yield e;
    }
    if (!empty && afterLast) yield separator;
  }
}

The problem is that if you have a [ButtonWidget(...), ButtonWidget(...)].intersperse(SpacerWidget(...), it won't work. You have to write <Widget>[ButtonWidget(...), ButtonWidget(...)].intersperse(SpacerWidget(...).
(If only we could write Iterable<S> intersperse<S super T>(S separator, ...).)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants