5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter mapとforEachにindexを付ける方法

Last updated at Posted at 2020-09-20

はじめに

備忘録です!

エクステンション生やします。

後述していますが、.asMap()を使えば以下必要ありませんでした。

extension IterableExtensions<E> on Iterable<E> {
  /// Like Iterable<T>.map but callback have index as second argument
  Iterable<T> mapIndex<T>(T Function(E e, int i) f) {
    var i = 0;
    return map((e) => f(e, i++));
  }

  void forEachIndex(void Function(E e, int i) f) {
    var i = 0;
    forEach((e) => f(e, i++));
  }
}

使い方

final hunterList = ['GON', 'KILLUA', 'CURARPIKT', 'LEORIO', 'HYSKOA'];

hunterList.forEach ((hunter, index) {
  debugPrint('${hunter}, ${index}');
});

// GON, 0
// KILLUA, 1
// CURARPIKT, 2
// LEORIO, 3
// HYSKOA, 4

追記:

@ntaoo さんからご指摘いただきました。
https://api.dart.dev/stable/2.2.0/dart-core/List/asMap.html
.asMap()でindexが取得できるようです。

final hunterList = ['GON', 'KILLUA', 'CURARPIKT', 'LEORIO', 'HYSKOA'];
hunterList.asMap().forEach((index, value) {
   debugPrint('${index} : ${value}')
});

// GON, 0
// KILLUA, 1
// CURARPIKT, 2
// LEORIO, 3
// HYSKOA, 4

わざわざExtensionはやす必要ありませんでした。
ありがとうございます。

5
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?