英文:
how to check if Map == the same other map (keys and values )
问题
例如,我有以下两个具有相同键和值的动态映射:
Map a = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
Map b = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
当我调用以下代码时:
print((a==b).toString());
为什么始终会打印出false
呢?
如何以正确的方式检查它,我需要知道这两个映射是否具有完全相同的键和值。
英文:
For example, I have the following two dynamic maps that have the same keys and values:
Map a = {
'name':'alex',
'products': {'type':'cars'},
'rate':100,
'others':['not yet']
};
Map b = {
'name':'alex',
'products': {'type':'cars'},
'rate':100,
'others':['not yet']
};
when i call
print((a==b).toString()); => always print false why ?
How to check it in the correct way I need to know if these two maps have the same keys and values exactly.
答案1
得分: 2
You can try DeepCollectionEquality类 在这里
示例:
import 'package:collection/collection.dart';
Map a = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
Map b = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
DeepCollectionEquality deepCollectionEquality =
const DeepCollectionEquality();
print(deepCollectionEquality.equals(a, b));
英文:
You can try DeepCollectionEquality class in here
example:
import 'package:collection/collection.dart';
Map a = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
Map b = {
'name': 'alex',
'products': {'type': 'cars'},
'rate': 100,
'others': ['not yet']
};
DeepCollectionEquality deepCollectionEquality =
const DeepCollectionEquality();
print(deepCollectionEquality.equals(a, b));
答案2
得分: 0
以下是翻译好的内容:
- 应该具有相同的长度(如果所有映射的长度都为 null,则返回 true)。
- 遍历任何一个映射的键列表,并在其他映射中检查相同的键-值对,如果它们之间的“与”操作在任何时候为 false,则返回 false。
- 最后返回 true(仅当步骤 2 中的所有“与”操作都返回 true 时才返回 true)。
或者,您可以使用包 https://api.flutter.dev/flutter/foundation/mapEquals.html。但唯一的缺点是它只接受两个映射作为输入。
英文:
You might need to do the following things(in the given order) in order to check whether two(or more) maps are equal or not
- should have same length(if lengths of all maps is null return true)
- iterate over the list of keys of any of the maps and check for the same key-value pairs in other maps, if "and" operation between them is false at any point then return false
- Return true in the end(this is returned only when all and operations in step 2 return true)
Alternatively you can use the package https://api.flutter.dev/flutter/foundation/mapEquals.html.
But the only drawback is that its takes only two maps as input
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论