比较List的相同结果<Map<String, Object>>不成立

问题描述 投票:0回答:1

我试图比较由 Map 组成的列表中的值,但结果总是返回 false,尽管我与之比较的值是相同的。我在这里做错了什么吗?

List<Map<String, Object>> orderList = [{"Nasi Goreng": 1}];
...
ElevatedButton(onPressed: () {
  print(orderList);
  assert(orderList[0] == {"Nasi Goreng": 1});
}, child: Text("+"))

我尝试使用

assert
contains
indexOf
,但所有这些都返回 false、false 和 -1。我预计其中之一至少应该返回 true 或返回该项目的索引(即 0),但我一直得到 false。我从运行断言得到的是:

Failed assertion: line 178 pos 68: 'orderList[0] == {"Nasi Goreng": 1}': is not true.
flutter list dart object
1个回答
0
投票

在 Dart 中使用比较时,“==”条件意味着对象的引用相同,而不是它们的值相同。 然而,有一个名为“collection”的类。所以,首先添加它:

dependencies:
  collection: ^1.15.0

然后,以下代码应该可以工作:

import 'package:collection/collection.dart';  // Import the collection package

List<Map<String, Object>> orderList = [{"Nasi Goreng": 1}];

ElevatedButton(
  onPressed: () {
    print(orderList);

    // Now we will use MapEquality to compare the map contents (not reference)
    final mapEquality = MapEquality();
    bool isEqual = mapEquality.equals(orderList[0], {"Nasi Goreng": 1});
    
    // Print whether the maps are equal
    print(isEqual);  // Now it should print true now

    // Assert based on map content equality, to be on the safe side
    assert(isEqual);
  },
  child: Text("+"),
)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.