在dart中,有任何等同于普通的东西:
enumerate(List) -> Iterator((index, value) => f)
or
List.enumerate() -> Iterator((index, value) => f)
or
List.map() -> Iterator((index, value) => f)
Run Code Online (Sandbox Code Playgroud)
看来这是最简单的方法,但是似乎不存在此功能仍然很奇怪。
Iterable<int>.generate(list.length).forEach( (index) => {
newList.add(list[index], index)
});
Run Code Online (Sandbox Code Playgroud)
编辑:
感谢@ hemanth-raj,我得以找到所需的解决方案。我将把它放在这里,供需要执行类似操作的任何人使用。
List<Widget> _buildWidgets(List<Object> list) {
return list
.asMap()
.map((index, value) =>
MapEntry(index, _buildWidget(index, value)))
.values
.toList();
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以创建一个同步生成器函数以返回一个可迭代
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. …
Run Code Online (Sandbox Code Playgroud) 我在网上搜索了很多答案。
我在字母列表上写了迭代,然后使用“地图”类将卡片放在屏幕上
在代码中,您可以看到我进行了一行操作,并使用“ map”将卡上所有的userBoard都打印到了屏幕上。我想在其中添加一些逻辑,所以我需要获取elemnt的ID(用于Taping事件)。有办法可以做到吗?
实际上我想通过userBoard获取元素的特定索引
码:
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: userBoard
.map((element) => Stack(children: <Widget>[
Align(
alignment: Alignment(0, -0.6),
child: GestureDetector(
onTap: (() {
setState(() {
// print("element=${element.toString()}");
// print("element=${userBoard[element]}");
});
}),
child: SizedBox(
width: 40,
height: 60,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Center(
child: Text(element,
style: TextStyle(fontSize: 30)),
)),
),
),
)
]))
.toList(),
)
],
),
Run Code Online (Sandbox Code Playgroud)
}
图片 -每张卡都是地图的“元素”。我想获取函数onTap的索引。
谢谢。