Get iteration index from List.map()

127,986

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

Another approach using List.generate:

var list = ['y', 'e', 's'];
var widgets = List.generate(list.length, (i) => Text(list[i]));
Share:
127,986
Shoham yetzhak
Author by

Shoham yetzhak

Updated on December 14, 2021

Comments

  • Shoham yetzhak
    Shoham yetzhak over 2 years

    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.

  • Shoham yetzhak
    Shoham yetzhak about 5 years
    I want to send a index of "userBoard" as a parameter userBoard.map((element) => Container( child: Text(element) //.... Some code and listener of button func(element_index);
  • Gökberk Yağcı
    Gökberk Yağcı almost 5 years
    It will be wrong when dublicate element in your list it returns first founded item's index.
  • jamesdlin
    jamesdlin over 4 years
    This would be very inefficient.
  • Henok
    Henok over 4 years
    dublicate elements must be checked for sure
  • Simple UX Apps
    Simple UX Apps over 4 years
    @jamesdlin Why is it inefficient?
  • jamesdlin
    jamesdlin over 4 years
    @SimpleUXApps Because list.indexOf must iterate over the list to find the specified element. Each list.indexOf call is O(n), and using it for each element of the list therefore would be O(n^2). This is inefficient since this operation could be easily done in O(n) time.
  • geisterfurz007
    geisterfurz007 almost 3 years
    This is inefficient. The default implementation iterates over the list to find the given item so you have O(n²) (if I am not completely off) for this in worst case. It's also inaccurate. Given final myList = [0, 1, 2, 1];, this will print 0, 1, 2, 1 instead of 0, 1, 2, 3.
  • NearHuscarl
    NearHuscarl over 2 years
    Where is the index?
  • CopsOnRoad
    CopsOnRoad over 2 years
    @NearHuscarl This may not directly answer what is asked in the title.
  • Jani
    Jani over 2 years
    A more up-to-date solution from the linked answer: "You can use the mapIndexed or forEachIndexed extension methods from the collection package."
  • Jani
    Jani over 2 years
    This should be the new accepted answer. I love how I always have to read the latest answers in Dart-related questions since the team keeps pushing out quality of life changes so fast.
  • jsgalarraga
    jsgalarraga about 2 years
    There's a much better approach from other answer here after dart released the collection package: stackoverflow.com/a/68357576/8494794
  • Amsakanna
    Amsakanna almost 2 years
    I like this better. Lemme add a link to this in my answer.
  • arg20
    arg20 almost 2 years
    please do not do this