Search code examples
loopsdictionaryindexingdartflutter

Get iteration index from List.map()


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

In the code you can see that I made a row, and using "map" printed all the userBoard on cards to the screen. I want to add some logic inside so I need to get the id of the element (for taping event). Is there a way that I can do that?

Actually, I want to get a specific index of element over userBoard.

Code:

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(),
            )
          ],
        ),
}

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


Solution

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

    Example

    final fruitList = ['apple', 'orange', 'mango'];
    final fruitMap = fruitList.asMap(); // {0: 'apple', 1: 'orange', 2: 'mango'}
    
    // To access 'orange' use the index 1.
    final myFruit = fruitMap[1] // 'orange'
    
    // To convert back to list
    final fruitListAgain = fruitMap.values.toList();
    

    Your Code

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

    References to other answers