美文网首页
Flutter中List.asMap同时获取下标和值

Flutter中List.asMap同时获取下标和值

作者: 志城 | 来源:发表于2022-03-03 10:06 被阅读0次
  • google到的文章都是一把抄,真是无力吐槽;
  • 先说我的结论:List().asMap().entries.map
  • List类:
 /**
   * Returns an unmodifiable [Map] view of `this`.
   *
   * The map uses the indices of this list as keys and the corresponding objects
   * as values. The `Map.keys` [Iterable] iterates the indices of this list
   * in numerical order.
   *
   *     List<String> words = ['fee', 'fi', 'fo', 'fum'];
   *     Map<int, String> map = words.asMap();
   *     map[0] + map[1];   // 'feefi';
   *     map.keys.toList(); // [0, 1, 2, 3]
   */
  Map<int, E> asMap();
  • Map类:
/**
   * The map entries of [this].
   */
  Iterable<MapEntry<K, V>> get entries;
  • List通过asMap返回的是一个Map对象,而Map对象有一个entries属性,通过entriesmap方法就可以同时拿到keyvalue了(也就是Listindexvalue

一般写法直接使用map方法:

  • 只能获取到value,无法获取到下标,这里肯定有人要说使用listindexOf也可以获取到下标,那当然可以,这里不讨论这种写法
["北京", "成都", "深圳", "上海", "杭州"]
                  .map((e) => PopupMenuItem(child: Text(e)))
                  .toList();

同时获取index和value的写法

["北京", "成都", "深圳", "上海", "杭州"]
                  .asMap()
                  .entries
                  .map((e) => PopupMenuItem(
                        child: Text(e.value),
                        value: e.key,
                      ))
                  .toList();

相关文章

网友评论

      本文标题:Flutter中List.asMap同时获取下标和值

      本文链接:https://www.haomeiwen.com/subject/rxmyrrtx.html