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 list interspersion as built in function #49900
Comments
Sounds like a possible extension on extension Intersperse<T> on Iterable<T> {
Iterable<T> intersperse(T separator) sync* {
var iterator = this.iterator;
if (iterator.moveNext()) {
yield iterator.current;
while (iterator.moveNext()) {
yield separator;
yield iterator.current;
}
}
}
} It's not perfect. If we had lower-bounded type variables, the signature should be The alternative is a static/constructor, say on factory Iterable.interspersed(Iterable<T> values, T separator) => () sync {
// The above, with this↦values.
}(); Not as easy to use: |
I think that interspersion is extremely useful and that the standard library should provide a way to intersperse. (we already have a specialization of interspersion for strings called String.join) There are many valuable modifications to the standard idea of interspersion that I've found to be useful:
For performance reasons it might make sense to intersperse in-place into a given list, and not to intersperse lazily on-demand on an Iterable. Unfortunately, I don't see how such extensions can be supported with an API as simple as a single Furthermore, the 'perfect' In response to the flutter related interspersion issues, I think that Row/Column and others should have a custom separator parameter because needing to intersperse is common enough and this would give the framework more freedom to optimize for these use-cases (e.g. so that separators don't have to be redrawn). It's complicated. |
Lasse wrote:
Within the context of Flutter, in practice, the List value that users want to intersperse with some element will mostly come from List literals (I claim this to be true based on personal experience and see here for some evidence: flutter/flutter#16957, flutter/flutter#95521). This special case has a safe solution, which is to provide an explicit type for the contents of the list: void main() {
// This would be inferred to Container, but Widget is what we want here.
// vvvvvvvv
final list = <Widget>[
Container(),
Container(),
]
.intersperse(const SizedBox())
.toList();
} (Perhaps this will be useful to someone that finds this issue) |
I find myself needing to use interspersion a lot in flutter. For example in cases where I can't use
ListView.separated
I can just dochildren.intersperse(SizedBox(height: 10));
I think the community at large could benefit from having this feature built into the language. This would spare us from having to add it to every project.The text was updated successfully, but these errors were encountered: