skip to Main Content

Contain method can not detect the object inside of list
What is the reason of that?

I expected to get the result of if block
enter image description hereLook at this picture as well.In the second picture it works

2

Answers


  1. You can override the == operator on Country like so to get it to work:

    class Country {
      bool? brotherCountry;
      String? name;
      Country(this.brotherCountry, this.name);
    
      @override
      bool operator ==(Object other) {
        if (other is Country) {
          return name == other.name && brotherCountry == other.brotherCountry;
        }
        return false;
      }
    
      @override
      int get hashCode => brotherCountry.hashCode ^ name.hashCode;
    }
    
    

    Alternatively, there’s this package https://pub.dev/packages/equatable, and you can use it like so:

    class Country extends Equtable {
      bool? brotherCountry;
      String? name;
      Country(this.brotherCountry, this.name);
    
      @override
      List<Object> props => [brotherCountry, name];
    }
    

    As pointed about by jamesdlin, it’s not because of call by value

    From Effective dart, it says:

    Any two objects that are equal must have the same hash code. Otherwise, maps and other hash-based collections will fail to recognize that the two objects are equivalent.

    Login or Signup to reply.
  2. it’s because your Contact object has no == relation between its instances,
    so trying to compare two instances like this:

    Contact(false, "") == Contact(false, "") // false
    

    And the contains method follows the same comparison I did to find if a list contains that object.

    It would help if you told Dart when two objects of that class should be considered equal to each other, by overriding the == operator like this:

    class Country {
      final bool? brotherCountry;
      final String? name;
      Country(this.brotherCountry, this.name);
      
      @override
      bool operator ==(covariant Country other) {
        return other.name == name && other.brotherCountry ==brotherCountry;
        
      }
    }
    

    now trying this:

    Country(false, "") == Country(false, "") // true
    

    and so on now the contains method will work as you expect

    [Country(false, ""), Country(false, "test")].contains(Country(false, "")); // true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search