在飞镖中有任何等同于共同点:
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)
});
编辑:
感谢@ hemanth-raj,我能够找到我想要的解决方案。我会把这个放在任何需要做类似事情的人身上。
List<Widget> _buildWidgets(List<Object> list) {
return list
.asMap()
.map((index, value) =>
MapEntry(index, _buildWidget(index, value)))
.values
.toList();
}
有一个asMap
方法,它将列表转换为一个映射,其中键是索引,值是索引处的元素。请查看文档here。
例:
List _sample = ['a','b','c'];
_sample.asMap().forEach((index, value) => f);
希望这可以帮助!
建立在@Hemanth Raj的答案上。
要将其转换回来,你可以做到
List<String> _sample = ['a', 'b', 'c'];
_sample.asMap().values.toList();
//returns ['a', 'b', 'c'];
或者,如果您需要映射函数的索引,则可以执行以下操作:
_sample
.asMap()
.map((index, str) => MapEntry(index, str + index.toString()))
.values
.toList();
// returns ['a0', 'b1', 'c2']
Lukas Renggli的more软件包包含许多有用的工具,包括“索引”,它可以完全满足您的需求。来自文档:
indexed(['a', 'b'], offset: 1)
.map((each) => '${each.index}: ${each.value}')
.join(', ');
(除非您有Smalltalk背景,否则可以忽略偏移量参数:-)。