在飞镖里,任何等同于普通的东西:
enumerate(List) -> Iterator((index, value) => f)
or
List.enumerate() -> Iterator((index, value) => f)
or
List.map() -> Iterator((index, value) => f)
这似乎是最简单的方法,但似乎仍然奇怪的是,这种功能将不存在。
Iterable<int>.generate(list.length).forEach( (index) => {
newList.add(list[index], index)
});
发布于 2019-02-27 06:57:17
有一个asMap
方法,它将列表转换为映射,其中键是索引,值是索引的元素。请看一下docs 这里。
示例:
List _sample = ['a','b','c'];
_sample.asMap().forEach((index, value) => f);
希望这能有所帮助!
发布于 2019-12-22 20:34:45
您可以从mapIndexed
包中使用collection
或forEachIndexed
扩展方法。请注意,与javascript的array.map()
或C#的IEnumerable.Select()
不同,索引是回调的第一个参数,而不是第二个参数:
import 'package:collection/collection.dart';
void main() {
final inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
final indexes = inputs.mapIndexed((index, element) => index).toList();
inputs.forEachIndexed((index, element) {
print('index: $index, element: $element');
});
print(indexes);
}
旧答案
从Dart 2.7开始,您可以使用方法扩展Iterable
的功能,而不必编写助手函数:
extension ExtendedIterable<E> on Iterable<E> {
/// Like Iterable<T>.map but the callback has index as second argument
Iterable<T> mapIndexed<T>(T Function(E e, int i) f) {
var i = 0;
return map((e) => f(e, i++));
}
void forEachIndexed(void Function(E e, int i) f) {
var i = 0;
forEach((e) => f(e, i++));
}
}
用法:
final inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
final results = inputs
.mapIndexed((e, i) => 'item: $e, index: $i')
.toList()
.join('\n');
print(results);
// item: a, index: 0
// item: b, index: 1
// item: c, index: 2
// item: d, index: 3
// item: e, index: 4
// item: f, index: 5
inputs.forEachIndexed((e, i) => print('item: $e, index: $i'));
// item: a, index: 0
// item: b, index: 1
// item: c, index: 2
// item: d, index: 3
// item: e, index: 4
// item: f, index: 5
发布于 2019-08-06 08:19:40
没有内置函数来获得迭代索引。
如果像我一样,您不喜欢只为一个简单的索引构建一个Map
(数据结构)的想法,那么您可能需要的是一个map
(函数),它为您提供索引。让我们把它称为mapIndexed
(就像Kotlin中的那样):
children: mapIndexed(
list,
(index, item) => Text("event_$index")
).toList();
mapIndexed
的实现很简单:
Iterable<E> mapIndexed<E, T>(
Iterable<T> items, E Function(int index, T item) f) sync* {
var index = 0;
for (final item in items) {
yield f(index, item);
index = index + 1;
}
}
https://stackoverflow.com/questions/54898767
复制相似问题