Testing Objects for Equality in Google Dart

Google Flutter -

Testing Objects for Equality in Google Dart

Testing Objects for Equality ('==')

If you want to be able to compare two Car objects for equality in this way:

car1 == car2 

and your equality test is:

‘car make and model should match’

 

then you should code it like this:

class Car {

 String _make;

 String _model;

 String _imageSrc;

 

 Car(this._make, this._model, this._imageSrc);

 

 operator ==(other) =>

     (other is Car) && (_make == other._make) && (_model ==     other._model);

 

int get hashCode => _make.hashCode ^ _model.hashCode ^ _imageSrc.hashCode;

 

}

 

HashCode

Note that when you override the ‘==’, you need to override the ‘hashCode’ method as well. If you don’t do that then Flutter will give you a warning.

You should override the two together because the collections framework uses the ‘hashCode’ method to determine equality, array indexes etc.   You don’t want equality working in one place and not the other.