When I retrieve some items there are some duplicates. I want to remove them but I can't. I have tried simple toSet().toList() solution but it does not work. Anything that works?
Article Model consists of:
final String id;
final String author;
final String caption;
The function code:
SearchItem(User user,int page,String searchfield,List<String> tags,bool tagsearch,int pl,int ph,bool searchbasedonlocation,bool priceactivated) async {
List<Article> articlesfinal = [];
if(tagsearch){searchfield = newtags(tags);}
final response = await http.get(Uri.parse("$url"), headers: <String, String>{'Content-Type': 'application/json');
final parsed = jsonDecode(utf8.decode(response.bodyBytes));
List<Article> users = parsed["results"] != null ? new List<Article>.from( parsed["results"].map((x) => Article.fromJSON(x))) : List<Article>();
final response2 = await http.get(Uri.parse("$url") ,headers: <String, String>{'Content-Type': 'application/json');
final parsed2 = jsonDecode(utf8.decode(response2.bodyBytes));
List<Article> users2 = parsed2["results"] != null ? new List<Article>.from( parsed2["results"].map((x) => Article.fromJSON(x))) : List<Article>();
users = users.toSet().toList();
users2 = users2.toSet().toList();
articlesfinal.addAll(users);
articlesfinal.addAll(users2);
return articlesfinal.toSet().toList();
}
CodePudding user response:
You'll have to override the equality operator in your model, otherwise it won't be able to know whether or not two objects of your model are equal. This package makes it easier for cases like this: equatable
After adding the package extend Equatable:
class Article extends Equatable
And then add properties you want to check for equality:
@override
List<Object?> get props => [id, author, caption];
CodePudding user response:
I have solved the issue by using hash function inside Article model
@override
operator ==(o) => o.id == id && o.caption== caption;
@override
int get hashCode => hashValues(id,caption);
And after that using articlesfinal.toSet().toList() solved the issue!
