枚举或映射Dart中具有索引和值的列表 [英] Enumerate or map through a list with index and value in Dart

查看:193
本文介绍了枚举或映射Dart中具有索引和值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在dart中,有任何与普通项等效的东西:

In dart there any equivalent to the common:

enumerate(List) -> Iterator((index, value) => f)
or 
List.enumerate()  -> Iterator((index, value) => f)
or 
List.map() -> Iterator((index, value) => f)

这似乎是最简单的方法,但

It seems that this is the easiest way but it still seems strange that this functionality wouldn't exist.

Iterable<int>.generate(list.length).forEach( (index) => {
  newList.add(list[index], index)
});

编辑:

由于@ hemanth-raj,我得以找到所需的解决方案。
我会把它放在这里给需要做类似事情的人。

Thanks to @hemanth-raj i was able to find the solution I was looking for. I'll put this here for anyone who needs to do something similar.

List<Widget> _buildWidgets(List<Object> list) {
    return list
        .asMap()
        .map((index, value) =>
            MapEntry(index, _buildWidget(index, value)))
        .values
        .toList();
}

或者,您可以创建一个同步生成器函数以返回可迭代的

Alternatively you could create a synchronous generator function to return a iterable

Iterable<MapEntry<int, T>> enumerate<T>(Iterable<T> items) sync* {
  int index = 0;
  for (T item in items) {
    yield MapEntry(index, item);
    index = index + 1;
  }
}

//and use it like this.
var list = enumerate([0,1,3]).map((entry) => Text("index: ${entry.key}, value: ${entry.value}"));


推荐答案

有一个 asMap 方法可将列表转换为映射,其中键是索引,值是索引处的元素。请在此处中查看文档。

There is a asMap method which converts the list to a map where the keys are the index and values are the element at index. Please take a look at the docs here.

示例:

List _sample = ['a','b','c'];
_sample.asMap().forEach((index, value) => f);

希望这会有所帮助!

这篇关于枚举或映射Dart中具有索引和值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆