与 python 中的 orderedDict 相比,flutter LinkedHashMap

flutter LinkedHashMap compared with orderedDict in python

自去年秋天以来,我就是颤抖的宝贝。当我们使用 flutter 类型时,它们通常会提供像 toString() 这样的通用功能。其中之一是'.runtimeType'但是这个'getting runtimeType'方法似乎不适用于发布模式,实际上在调试模式下效果很好。

假设我们有像 Map amIMap = {"key": "is key", "value": "is value",}; 这样的法线贴图 通常我们认为这个 var 的类型是 'Map',但是 print(amIMap.runtimeType); 方法在调试模式下(这看起来不像在发布模式下工作)打印不是 'Map' 而是像 LinkedHashMap,这可能因开发环境而略有不同,但与 LinkedHashMap.

的概念基本相同

那么问题来了。在这个 link 'https://api.flutter.dev/flutter/dart-collection/LinkedHashMap-class.html' 中,从上面的情况来看,打印的类型似乎是 Dart 团队实际想要的东西,而且看起来真的很像 python 中的 orderedDict。通过这个问题,我想确保 LinkedHashMap 这个概念可以安全使用。我的意思是,我想知道带有键及其对应值的对的顺序是否安全地保持不变,就像 python 中的 'orderedDict' 一样,无论调试、配置文件、发布模式等环境如何、dartpad,甚至 android、ios、macos、linux、window、web!

等平台

因为我已经看到 runtimeType 在我的应用程序的发布模式下不能很好地工作,我担心在发布模式下 sdk 可能会忘记键值对的顺序,就像 runtimeType方法。

我问这个问题的原因是我需要强制对的顺序与我在 IDEA 中的 dart 代码完全相同,这样我就可以将它们转换成相同的格式 json 字符串,然后使用 crypto 包的 sha256 哈希方法对 json 字符串进行哈希处理,这些字符串都具有完全相同的对顺序。地图的顺序必须在散列之前保持不变。让我害怕的是,颤动往往会因环境而异。此外,当我使用 firestore 插件时,我必须手动从 firestore 中对地图进行排序,因为它们与可以通过 firebase 控制台检查的顺序不同。看起来这些问题的背景相似。所以我需要 bool 值,如果 linkedHashMap 即使在发布模式下也要保存我的地图对的顺序,而不管 flutter 2.0 的各种平台,就像 python.

中的 orderedDict

希望这个领域的任何大师都能以完全确信的经验回答这个问题。如果我在这个问题上留下了不清楚甚至错误的地方,我将非常感谢您的评论,

提前致谢[:

首先,除了调试之外,您不应该将 .runtimeType 用于任何其他用途。如您所见,输出实际上并不稳定,因此很少用于任何用途。如果您需要检查给定对象是否与给定的 class.

兼容,则应改为使用 is 运算符

二、Map() constructor (the {} syntax does the same) in Dart is documented to be creating an instance of LinkedHashMap。由于这是标准 SDK 和语言设计的一部分,因此不会更改。此外,此行为在 Dart 为 运行.

的所有平台上都是稳定的

但是,如果您想确保始终使用 LinkedHashMap, you can just explicit create an instance of LinkedHashMap,请从 dart:collection 导入 class。

LinkedHashMap 记录为:

The insertion order of keys is remembered, and keys are iterated in the order they were inserted into the map. Values are iterated in their corresponding key's order. Changing a key's value, when the key is already in the map, does not change the iteration order, but removing the key and adding it again will make it be last in the iteration order.