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

2022-03-03  本文已影响0人  志城
 /**
   * 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();
/**
   * The map entries of [this].
   */
  Iterable<MapEntry<K, V>> get entries;

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

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

同时获取index和value的写法

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

猜你喜欢

热点阅读