首页 > 解决方案 > 我可以在地图键中使用对象吗?

问题描述

我有一张像这样的地图:

Map<Coordinates, Offset> myMap = {someCoordinates: someOffset, ...};

我想通过坐标得到一个偏移量(其中坐标是一个简单的类,带有 int x 和 int y)

...
Offset someOffset = myMap[someCoordinaets];

但它返回null。我做错了什么?我可以在地图键中使用对象吗?

编辑 这里是我的坐标类

class Coordinates {
  final int col;
  final int row;

  Coordinates(this.col, this.row);

  int getCol() {
    return col;
  }

  int getRow() {
    return row;
  }
}

解决方案:

import 'package:quiver/core.dart';

class Coordinates {
  final int col;
  final int row;

  Coordinates(this.col, this.row);
  
// solution
  bool operator ==(o) => o is Coordinates && col == o.col && row == o.row;
  int get hashCode => hash2(col.hashCode, row.hashCode);

  int getCol() {
    return col;
  }

  int getRow() {
    return row;
  }
}

标签: dart

解决方案


推荐阅读