Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
Shoham yetzhak Avatar asked Mar 04 '19 20:03

Shoham yetzhak


People also ask

How do you find an index on a map?

Index inside map() Function The index is used inside map() method to state the position of each element in an array, but it doesn't change the original array. Syntax: array. map(function(currentelement, index, arrayobj) { // Returns the new value instead of the item });


4 Answers

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

  • I like this answer better. Please take a look.
  • If you want in multiple places try extending like this.
  • Alternatively, you could also try the dart collection approach.
like image 188
Amsakanna Avatar answered Nov 02 '22 23:11

Amsakanna


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()
like image 34
FireHsia Avatar answered Nov 03 '22 01:11

FireHsia


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.

like image 22
geisterfurz007 Avatar answered Nov 03 '22 00:11

geisterfurz007


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.

like image 36
Andrey Gordeev Avatar answered Nov 02 '22 23:11

Andrey Gordeev