English 中文(简体)
我如何检查地图清单是否* 含有Dart的具体关键内容?
原标题:How do I check if a List of Maps does *not* contain a specific key in Dart?
  • 时间:2023-08-10 22:10:01
  •  标签:
  • flutter
  • dart

How do I check if a List of Maps List<Map<String, List<CustomObject>>> listOfMaps does not contain a specific key?

我正在通过<代码>listOfMaps查询,如果地图含有一个具体的关键。

If so I write over the values (code below):

listOfMaps.forEach((map) {
      if (map.containsKey(key)) {
        // write over values...
      }
    });

然而,如果名单 其中,我不想在名单上添加新的地图。

listOfMaps.add(
        {key: [
      // Custom Objects
    ]}
    );

如何核对<代码>listOfMaps?not是否包含具体的关键?

*Edit:

listOfMaps = [
{ map1 : [listOfCustomObjects]},
{ map2 : [listOfCustomObjects]},
{ map3 : [listOfCustomObjects]},
]

I am now dealing with new data: { map4 : [listOfCustomObjects]}

if listOfMaps doesn t contain key map4 I want to add a map, if listOfMaps does contain map4 already I want to write over the values.

同样值得注意的是,我知道,清单OfMaps中的每个地图将包含 仅1 钥匙。

问题回答

Simple enough.

listOfMaps.update( map4 , (old) => (old with new), ifAbsent: () => new); 

EDIT: ooops。 这并不是要解决的问题。 我只想离开这里,因为人们忘记了这项工作,解决一些问题。 iii

I d also suggest that the ordering of the maps is likely insignificant, so this should really just be a map with keys, not a list of maps with a single key, and then my solution is applicable.

解决办法虽然可行,但似乎很少见...... 如果人人都能以更简单的方式行事,我就知道......。

  checkIfListOfMapsContainsKey({
    required String key,
    required List<Map<String, List<CustomObject>>> listOfMaps,
  }) {
    bool hasKey = false;
    listOfMaps.forEach((map) {
      if (map.containsKey(key)) {
        hasKey = true;
      }
    });
    return hasKey;
  }

之后:

bool hasKey = checkIfListOfMapsContainsKey(
          key: key,
          listOfMaps: listOfMaps,
        );
        if (hasKey == false) {
          listOfMaps.add({ map4 : [listOfObjects]});
          
        }

我可以考虑以下几种方式:

使用<代码>Iterable.any(......)。

if (listOfMaps.any((m) => m.containsKey(key))) {
  // Do something
} else {
  // Add new map to listOfMaps
}

Use a flag:

bool found = false;
listOfMaps.forEach((map) {
  if (map.containsKey(key)) {
    found = true;
    // write over values...
  }
});
if (!found) {
  listOfMaps.add(
    {key: [
      // Custom Objects
    ]}
  );
}




相关问题
Flutter App cannot be installed on Android TV

I m building a Flutter app that should support Android TV and Mobile devices. Despite Google Play shows that it is supported, I cannot install app on my MiBox device. While trying to install it, both ...

Moving the icon button to the right causes rendering issues

I am trying to align the icon button to the right of the Text field, I tried the row which made the icon button not centered vertically and now I am trying out the Stack widget. Here is my code - ...

热门标签