Is it possible to use .equals() method like Java in Dart

3,851

Solution 1

Dart language don't have equals method. According this article, I have to use Equatable Package.

Solution 2

@override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is Class &&
              runtimeType == other.runtimeType &&
              id == other.property;

@override
int get hashCode => property.hashCode;
Share:
3,851
Trần Đức Tâm
Author by

Trần Đức Tâm

$ python analyze @rikimaru Dartino by day, Pythonista by night! (last update 2020/28/02) [Full-time Mobile developer (Android/Flutter)] at NTQ Japan Type 'help', 'profile' or 'idea' for more information >>>if profile.allow_accept: ... print('\n'.join([bio for bio in profile.bio if bio.public]) [1] Hobby: Dota2・Cooking・Reading・Music [2] Target: Become Solution Architecture [3] Location: Yokohama, Japan

Updated on December 15, 2022

Comments

  • Trần Đức Tâm
    Trần Đức Tâm over 1 year

    I'm a Java developer and the newbie in Dart.

    When I compare two objects in Dart, it only has == operator which helps me compare two logical memory addresses of two objects in Dart. How can I compare two objects to be the same like Java without be preparing this code below? It makes me tired to prepare entity's class so I wonder that have any Dart's ways for that?

    class MyClass {
        final MySubClass mySubClass;
    
        MyClass({this.mySubClass});
    
        bool equals(Object other) => identical(this, other) || other is MyClass && runtimeType == other.runtimeType && something.equals(other.mySubClass);
    }
    
    class MySubClass {
        final String something;
    
        MySubClass({this.something});
    
        bool equals(Object other) => identical(this, other) || other is MySubClass && runtimeType == other.runtimeType && something == other.something;
    }
    
  • Admin
    Admin over 4 years
    equatable uses same == operator
  • Admin
    Admin over 4 years
    article quote Equatable overrides == and hashCode for you so you don’t have to waste your time writing lots of boilerplate code. so you said I have to use Equatable Package not true, you could use it but you don't have to used it
  • Trần Đức Tâm
    Trần Đức Tâm over 4 years
    Some one did edited my question. I want an equal method which compare the value but not memory location. :/
  • Stephen Ostermiller
    Stephen Ostermiller about 2 years
    A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation.