Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Dart List - How to check if a list contains an object

Tags:

list

flutter

dart

I wrote a function which returns true if an element is present in a list. I created an earlier version in which the list contained "ints" and it worked fine. Now I have a list of "complex" objects, and it seems it never detects if the object is present. Here is the code :

bool addNewWordToBufferCarnetList(int? wordId) {
    CarnetWords newWord =
        CarnetWords(iD: wordId!, wrong: 0, right: 0, mastery: 0);
         if (_bufferCarnetList.contains(newWord) == true) {
          return false;
    } else {
      _bufferCarnetList.add(newWord);
      notifyListeners();
      return true;
    }
  }

Is there another way to see if the list contains the object ?

like image 583
SylvainJack Avatar asked Dec 21 '25 20:12

SylvainJack


1 Answers

As suggested and explained by pskink, I had to override the == operator in my CarnetWords class for the "equality" to function. Here is the code :

class CarnetWords {
 @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    if (runtimeType != other.runtimeType) return false;
    return other is CarnetWords && other.iD == iD;
  }
 @override
  int get hashCode => iD.hashCode;

  int? iD;
  int? wrong;
  int? right;
  double? mastery;
  CarnetWords(
      {@required this.iD,
      @required this.wrong,
      @required this.right,
      @required this.mastery});
}

Thanks pskink for your help and patience !

like image 156
SylvainJack Avatar answered Dec 23 '25 13:12

SylvainJack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!