1

Most languages provide something like this apples.map((apple, index) => {}). What would be Dart's equivalent of identifying the index within a map or forEach?

Someone has offered apples.asMap().map((apple, index) => {}) however that returns an unmodifiable version of the map, which is not suitable when I'm trying to map a list to produce widgets .toList() inside children: of a Column.

Jesse
  • 2,690
  • 9
  • 15
  • 28
  • 1
    `.asMap` is the proper way to go. Map, filter, reduce and so on are functional-like tools. They do not modify the original structure, and that's by design. Instead, they return a copy of the original structure. If you need modified elements, just keep the return value of `asMap`. – Arthur Attout Jul 27 '19 at 11:54

2 Answers2

2

One way to use the index and value of a list item is to use the new collection for construct. The code would look something like this:

Widget build(BuildContext context) {
  final list = ['Mango', 'Orange', 'Apple'];

  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Column(
      children: <Widget>[
        for (int i = 0; i < list.length; i++)
          ListTile(title: Text('${list[i]} has index $i')),
      ],
    ),
  );
}

For this to work you'll need to update your minimum Dart SDK version in your pubspec.yaml like so:

environment:
  sdk: ">=2.3.0 <3.0.0"
aubykhan
  • 254
  • 2
  • 6
  • Thanks I'll give that a go, I've ended up just creating a separate for loop outside and adding all the widgets to a ist to be used as a child. This might look cleaner. Cheers – Jesse Jul 28 '19 at 07:00
  • These new constructs are part of Dart’s UI as Code philosophy and are recommended a well. If my answer serves your purpose, can you mark it as the right answer? – aubykhan Jul 28 '19 at 17:10
-1

I'm not sure I entirely understand what you're trying to do, but map and forEach are defined on Iterable, and the elements of an Interable aren't necessarily ordered, so providing an index for each element doesn't necessarily make sense. For example, if the Iterable is a Set then the elements have no order.

I don't quite get why you need the index in your particular example. If you expand your example, maybe I'll understand.

Tom Robinson
  • 531
  • 3
  • 7
  • Having an index in a `map` could be useful for numerous reasons that have nothing to do with the actual index of the item in the original list. E.G. : knowing how many items have been seen previously to the current one, creating auto-increment IDs, knowing if the current item is at an even or odd index, etc. – Arthur Attout Jul 27 '19 at 11:51