Enumerate or map through a list with index and value in Dart

后端 未结 8 2144
难免孤独
难免孤独 2020-12-08 01:28

In dart there any equivalent to the common:

enumerate(List) -> Iterator((index, value) => f)
or 
List.enumerate()  -> Iterator((index, value) =>          


        
相关标签:
8条回答
  • 2020-12-08 02:19

    Building on @Hemanth Raj answer.

    To convert it back you could do

    List<String> _sample = ['a', 'b', 'c'];
    _sample.asMap().values.toList(); 
    //returns ['a', 'b', 'c'];
    

    Or if you needed the index for a mapping function you could do this:

    _sample
    .asMap()
    .map((index, str) => MapEntry(index, str + index.toString()))
    .values
    .toList();
    // returns ['a0', 'b1', 'c2']
    
    0 讨论(0)
  • 2020-12-08 02:20

    There is a asMap method which converts the list to a map where the keys are the index and values are the element at index. Please take a look at the docs here.

    Example:

    List _sample = ['a','b','c'];
    _sample.asMap().forEach((index, value) => f);
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题