【问题标题】:How to properly override a class so that is uniquely added to a Map in Flutter [Dart]如何正确覆盖一个类,以便在 Flutter [Dart] 中唯一地添加到地图中
【发布时间】:2022-01-08 17:29:48
【问题描述】:

我想在 Flutter 中创建一个 Map 并将 activityProject 唯一地存储在地图中。您可以在下面看到一个截断的代码。

void main() {
  Map<ActivityProject, int> timesheet = Map.identity();

  timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 1);
  timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 2);
  timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 3);

    
  timesheet.entries.forEach((element) {
    print("Hashcode: ${element.key.hashCode}" );
    print(
        "Key: ${element.key.activity}-${element.key.project}, Value: ${element.value}");
  });
}

ActivityProject类定义如下

class ActivityProject {
  String activity;
  String project;

  ActivityProject(this.activity, this.project);

  @override
  bool operator ==(Object other) =>
      other is ActivityProject &&
      other.activity == activity &&
      other.project == project;

  @override
  int get hashCode => hashValues(activity, project);
}

我已经覆盖了“==”和hashCode,但即使哈希码相同,值也会放在地图中。

输出:

Hashcode: 176486800
Key: activity-project, Value: 1
Hashcode: 176486800
Key: activity-project, Value: 2
Hashcode: 176486800
Key: activity-project, Value: 3

任何建议都将受到高度赞赏。

【问题讨论】:

    标签: flutter dart hashmap flutter-web


    【解决方案1】:

    这里的问题是您使用的是Map.identity()。在Map<K, V>.identity constructor 上阅读此处的文档。

    身份映射使用相同的相等性和 identityHashCode 作为键的哈希码,而不是键的内在 Object.== 和 Object.hashCode。

    根据文档,使用Map.identity 构建的地图不使用== 和hashCode。

    你应该像这样定义你的地图:

    Map<ActivityProject, int> timesheet = {};
    

    【讨论】:

    • 你是对的!谢谢。
    猜你喜欢
    • 2021-11-13
    • 2020-05-02
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-08-27
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多