How to convert a List into a Map in Dart

前端 未结 4 2055
醉酒成梦
醉酒成梦 2021-01-01 08:44

I looking for an on-the-shelf way to convert a List into a Map in Dart.

In python for example you can do:

l= [ (\'a\',(1,2)), (\'b\'         


        
相关标签:
4条回答
  • 2021-01-01 09:13

    In Dart 1.1, you can use this constructor of Map:

    new Map.fromIterable(list, key: (v) => v[0], value: (v) => v[1]);
    

    This would be closest to your original proposal.

    0 讨论(0)
  • 2021-01-01 09:15

    Another possibility is to use the Map.fromEntries() constructor:

    final result = Map.fromEntries(l.map((value) => MapEntry(value[0], value[1])));
    
    0 讨论(0)
  • 2021-01-01 09:26

    You can use Map.fromIterable:

    var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);
    

    or collection-for (starting from Dart 2.3):

    var result = { for (var v in l) v[0]: v[1] };
    
    0 讨论(0)
  • 2021-01-01 09:32

    There is not yet a concept of tuples or pairs in dart (other than a two element Iterable). If Dart had such a concept, then issue 7088 proposes to solve this with a Map.fromPairs constructor.

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