gpt4 book ai didi

flutter - Dart 中的多级 map 或 map 列表?

转载 作者:行者123 更新时间:2023-12-03 03:15:39 27 4
gpt4 key购买 nike

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

{
'country': 'Japan',
'city': 'Tokyo',
'Latitude': 35.6762,
'Longitude': 139.6503,
'utcOffset': 9
}

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

1) map 列表:

List<Map<String, dynamic>> locations = [
{
'country': 'Japan',
'city': 'Tokyo',
'Latitude': 35.6762,
'Longitude': 139.6503,
'utcOffset': 9
}
];

或多级数据对象

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
},
};

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

最佳答案

我通常使用Map当我想要键值对时,因为我可以直接通过键获取值。例如,如果您有 Map的雇员,如果您将雇员 ID 作为 key ,则可以轻松访问它。专门用于搜索,或用于下拉,这很优雅。

大多数时候如果我能避免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"]));

这里有关于这个的文档:

Map<K, V> class

A collection of key/value pairs, from which you retrieve a value using its associated key.

There is a finite number of keys in the map, and each key has exactly one value associated with it.

Maps, and their keys and values, can be iterated. The order of iteration is defined by the individual type of map.

List<E> class

An indexable collection of objects with a length.

Subclasses of this class implement different kinds of lists. The most common kinds of lists are:

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.

The default growable list, as returned by new List() or [], keeps an internal buffer, and grows that buffer when necessary. This guarantees that a sequence of add operations will each execute in amortized constant time. Setting the length directly may take time proportional to the new length, and may change the internal capacity so that a following add operation will need to immediately increase the buffer capacity. Other list implementations may have different performance behavior.

关于flutter - Dart 中的多级 map 或 map 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59768587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com