它基本上只是一个循环中的一个循环,它遍历每个可迭代对象,找到内部可迭代对象的每个内部元素,然后将其作为单个展开的可迭代对象返回。
我找不到expand 的源代码,但是在我的darq 包中,您可以使用selectMany 方法看到相同的概念(这是因为selectMany 只是expand 与传递给选择器的附加索引)。至于 Dart 的 expand 是如何工作的,请忽略所有处理 index 的部分。
extension SelectManyExtension<T> on Iterable<T> {
/// Maps elements in an iterable to collections and then flattens those
/// collections into a single iterable.
///
/// During iteration, the [selector] function is provided each value in the iterable
/// along with the index of the value in the iteration. The
/// returned collection of that function is then iterated over, and each
/// value in that iteration is provided as the next element of the
/// resulting iterable. The result is all of the collections flattened so that
/// their values become elements in a single iterable.
///
/// Example:
///
/// void main() {
/// final list = ['abc', 'de', 'f', 'ghij'];
/// final result = list.selectMany((s, i) => s.iterable);
///
/// // Result: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
/// }
Iterable<TResult> selectMany<TResult>(
Iterable<TResult> Function(T element, int index) selector) sync* {
var index = 0;
for (var v in this) {
yield* selector(v, index++);
}
}
}
var list = [[1, 2, 3], [4, 5], [6]];
var flattened = list.selectMany((inner, idx) => inner);
// flattened = [1, 2, 3, 4, 5, 6]