Flutter-从List.map()获取迭代索引 [英] Flutter - Get iteration index from List.map()

查看:797
本文介绍了Flutter-从List.map()获取迭代索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索了很多答案。

I searched alot on net for answer.

我在字母列表上编写了迭代,并使用地图
类在屏幕上放置了卡片

I wrote iteration on list of letters and put inside cards on screen using "map" class

在代码中,您可以看到我做了一行,并使用 map在卡片上的所有userBoard上都打印到了屏幕上。
我想在里面添加一些逻辑,所以我需要获取元素的ID(用于Taping事件)。
有什么方法可以做到?

In the code you can see that i made a row and using "map" printed aall the userBoard on cards to the screen. I want to add some logics inside so i need to gett the id of the elemnt (for taping event). Theres a way that i can do taht?

实际上我想通过userBoard获取特定的元素索引

Actually i want to get a specific index of element over 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(),
        )
      ],
    ),

}

图片-每张卡都是地图的元素。我想获取函数onTap的索引。

Picture - each card is "element" of the map. I want to get the indexes for the function onTap.

谢谢。

推荐答案

要访问索引,您需要使用 asMap 运算符。

To get access to index, you need to convert your list to a map using the asMap operator.

示例

final fruitList = ['apple', 'orange', 'mango'];
final fruitMap = myList.asMap(); // {0: 'apple', 1: 'orange', 2: 'mango'}

// To access 'orange' use the index 1.
final myFruit = fruitMap[1] // 'orange'

// To convert back to list
fruit fruitListAgain = fruitMap.values.toList();

您的代码

userBoard.asMap().map((i, element) => MapEntry(i, Stack(
  GestureDetector(onTap: () {
    setState(() {
      // print("element=${element.toString()}");
      // print("element=${userBoard[i].toString()}");
    });
  }),
))).values.toList();

这篇关于Flutter-从List.map()获取迭代索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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