Home > Back-end >  search in a list .contains return false
search in a list .contains return false

Time:06-16

I have a list of this model List<AnimeModel> animeModels=[];

AnimeModel animeModel=AnimeModel(id: "id", name: "name", image: "image");

after adding this model to the list when I do this it returns false why ?

if(animeModels.contains(animeModel)

CodePudding user response:

Does AnimeModel properly implement == and hashCode? My guess is that it does not and that's why. Unless you're initializing const instances, Dart does object equality based on identity unless those methods are implemented.

CodePudding user response:

This snippet may help you understand your problem.

  var animemodel = AnimeModel(id: "0", name: "One", image: "img");
  var animemodel2 = AnimeModel(id: "2", name: "Two", image: "Img2");
  var list = [animemodel, animemodel2];
  
  print("${list.contains(animemodel)}"); //Will return True
  
  var animemodel3 = AnimeModel(id: "0", name: "One", image: "img");
  
  print("${list.contains(animemodel3)}"); //Will return False

If you want animemodel3 to return true, you should override those two methods in your AnimeModel class :

  bool operator ==(o) => o is AnimeModel && name == o.name && id == o.id;
  int get hashCode => hash2(id.hashCode, name.hashCode);
  • Related