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.


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();

You can get index use list.indexOf when the list has no duplicate elements。

Example

userBoard.map((element) {
  // get index
  var index = userBoard.indexOf(element);
  return Container(

  );
}).toList()

The easiest approach if you want to iterate

We can extend Iterable with a new function:

import 'dart:core';

extension IndexedIterable<E> on Iterable<E> {
  Iterable<T> mapIndexed<T>(T Function(E e, int i) f) {
    var i = 0;
    return map((e) => f(e, i++));
  }
}

Usage:

myList.mapIndexed((element, index) {});

Taken from here.


Dart has released the collection package that comes with a mapIndexed extension to all Iterables.

import 'package:collection/collection.dart';

void main() {
  final fruitList = ['apple', 'orange', 'mango'];
  final withIndices = fruitList.mapIndexed((index, fruit) => "$index - $fruit");
  print(withIndices);
}

(DartPad)

The package comes with all sorts of handy extensions and useful tools to work with collections.