Dart 中的多级地图或地图列表?

Ahm*_*ama 2 dart flutter

我有一个这样的位置数据地图:

{
  'country': 'Japan',
  'city': 'Tokyo',
  'Latitude': 35.6762,
  'Longitude': 139.6503,
  'utcOffset': 9
}
Run Code Online (Sandbox Code Playgroud)

女巫是存储这些数据的正确解决方案,为什么?

1)地图列表:

List<Map<String, dynamic>> locations = [
 {
      'country': 'Japan',
      'city': 'Tokyo',
      'Latitude': 35.6762,
      'Longitude': 139.6503,
      'utcOffset': 9
    }
];
Run Code Online (Sandbox Code Playgroud)

或多级数据对象

var locations = {
{
      'country': 'Egypt',
      'city': 'Cairo',
      'Latitude': 30.033333,
      'Longitude': 31.233334,
      'utcOffset': 2
    },
    {
      'country': 'Thailand',
      'city': 'Bangkok',
      'Latitude': 13.7563,
      'Longitude': 100.5018,
      'utcOffset': 7
    },
};
Run Code Online (Sandbox Code Playgroud)

以及如何访问这两种情况下的数据?

Bla*_*nka 5

Map我通常在想要有键值对时使用,因为我可以直接通过键获取值。举个例子,如果您有Map员工,并且将员工 ID 作为密钥,那么您可以轻松访问它。特别是对于搜索或下拉,这很优雅。

大多数时候,如果我可以避免Map,我会使用List,因为它对我来说很容易处理大量数据(在 flutter 中,我可以轻松地将列表扔到 ListView 中)。

但根据场景的不同,两者都有自己的优点。并注意Map不能有重复的键,哪里List没有这样的限制(例如:Map可以用来避免重复)。

  var locations = {
    {
      'country': 'Egypt',
      'city': 'Cairo',
      'Latitude': 30.033333,
      'Longitude': 31.233334,
      'utcOffset': 2
    },
    {
      'country': 'Thailand',
      'city': 'Bangkok',
      'Latitude': 13.7563,
      'Longitude': 100.5018,
      'utcOffset': 7
    },
  };

  for (var element in locations) {
    print(element["country"]);
  }

  // or

  locations.forEach((element) => print(element["country"]));
Run Code Online (Sandbox Code Playgroud)

这是文档包含的内容:

Map<K, V>班级

键/值对的集合,您可以使用其关联的键从中检索值。

映射中的键数量有限,并且每个键都有一个与其关联的值。

映射及其键和值可以迭代。迭代的顺序由映射的各个类型定义。

List<E>班级

具有长度的可索引对象集合。

该类的子类实现不同类型的列表。最常见的列表类型是:

Fixed-length list. An error occurs when attempting to use operations that can change the length of the list.

Growable list. Full implementation of the API defined in this class.
Run Code Online (Sandbox Code Playgroud)

List()由 new或返回的默认可增长列表[]保留一个内部缓冲区,并在必要时增长该缓冲区。这保证了一系列加法操作将在摊余常数时间内执行。直接设置长度可能会花费与新长度成比例的时间,并且可能会改变内部容量,使得后续的添加操作将需要立即增加缓冲区容量。其他列表实现可能具有不同的性能行为。