0

I have a map like:

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

And i want to get an offset by coordinates (where coordinates is a simple class with int x and int y)

...
Offset someOffset = myMap[someCoordinaets];

but it returns null. What i'm doing wrong? Can i use an object in the map key?

EDIT here is my Coordinates class

class Coordinates {
  final int col;
  final int row;

  Coordinates(this.col, this.row);

  int getCol() {
    return col;
  }

  int getRow() {
    return row;
  }
}

Solution:

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;
  }
}
  • Have you properly implemented `==` and `hashCode` in the `Coordinates` class? Even if the two objects' variables have the same values they are still not equal – Mattia Mar 17 '21 at 16:15
  • Mattia, i edited a question and add my Coordinates class there – Кадыр Атаханов Mar 17 '21 at 16:27
  • Check here how to implement the `==` and the `hashCode` operators https://stackoverflow.com/a/22999113/8745788 or you might want to implement the [Equatable](https://pub.dev/packages/equatable) package with handles that for you – Mattia Mar 17 '21 at 16:37
  • No, indeed in dart _every it an object_, but in your case, even if do eg. `Coordinates(1, 1) == Coordinates(1, 1)`, it will return false, because they are still different objects – Mattia Mar 17 '21 at 16:43
  • i solved my problem, thank you sir! – Кадыр Атаханов Mar 17 '21 at 16:47

0 Answers0