Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why doesn't .map or .forEach expose an index? #33965

Closed
lukepighetti opened this issue Jul 24, 2018 · 3 comments
Closed

Why doesn't .map or .forEach expose an index? #33965

lukepighetti opened this issue Jul 24, 2018 · 3 comments
Labels
closed-as-intended Closed as the reported issue is expected behavior

Comments

@lukepighetti
Copy link

No description provided.

@matanlurey matanlurey added the closed-as-intended Closed as the reported issue is expected behavior label Jul 24, 2018
@matanlurey
Copy link
Contributor

Both of these functions are actually on Iterable, and inherited through List.

It is possible to have an Iterable without a definitive length (or index, of any sort). For example, imagine a virtual-scrolling list. Of course, it is very easy to write such functionality yourself, if you'd like:

void forEachIndex<T>(Iterable<T> elements, void Function(T, int) forEach) {
  var i = 0;
  for (final element in elements) {
    forEach(element, i++);
  }
}

void example(Iterable<String> elements) {
  forEachIndex(elements, (e, i) {

  });
}

You might also find following this useful: #9991, then you'd do:

import 'package:your_package/your_package.dart';

void example(Iterable<String> elements) {
  elements.forEachIndex((el, i) { ... });
}

@alan-knight
Copy link
Contributor

The asMap method probably does what you want.

  var thing = [5,4,3,2,1];
  thing.asMap().forEach((k, v) => print("$k : $v"));

0 : 5
1 : 4
2 : 3
3 : 2
4 : 1

@xqdd
Copy link

xqdd commented Aug 11, 2018

 items: [
            ["HOME", Icons.home],
            ["MESSAGE", Icons.message],
            ["READ", Icons.chrome_reader_mode],
            ["ACITIVTY", Icons.local_activity],
            ["ME", Icons.person],
          ]
              .asMap()
              .map<int, BottomNavigationBarItem>(
                  (k, v) => MapEntry(k, _genBottomBarItem(k, v[0], v[1])))
              .values
              .toList(),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-as-intended Closed as the reported issue is expected behavior
Projects
None yet
Development

No branches or pull requests

4 participants