I have following code
class FavoriteItem {
String headline;
String content;
String link;
String publisheddate;
FavoriteItem({this.headline, this.content, this.link, this.publisheddate});
toJSONEncodable() {
Map<String, dynamic> m = new Map();
m['headline'] = headline;
m['content'] = content;
m['link'] = link;
m['publisheddate'] = publisheddate;
return m;
}
}
class FavoriteList {
List<FavoriteItem> items;
FavoriteList() {
items = new List();
}
toJSONEncodable() {
return items.map((item) {
return item.toJSONEncodable();
}).toList();
}
}
And i have initiated the class like this
final FavoriteList favlist = new FavoriteList();
and i populate favlist
with following code from json
if (items != null) {
(items as List).forEach((item) {
final favoriteitem = new FavoriteItem(headline: item['headline'], content: item['content'], link: item['link'], publisheddate: item['publisheddate']);
favlist.items.add(favoriteitem);
});
}
Problem
What I want to do is to check if object favoriteitem
already exist in favlist
before adding.
I tried using -
favlist.items.contains
favlist.items.indexof
but didn't work
I am new to flutter/dart, can anybody please help me on this
The contains() method is used to check if an element occurs in a list. This method takes one parameter and returns a boolean value indicating whether or not that item is found in the list.
To get an element at specific index from a List in Dart, call elementAt() method on this list and pass the index as argument. elementAt() method returns the element. If the index is out of range for the list, then elementAt() throws RangeError .
favlist.items.contains
and favlist.items.indexof
are not working because I assume you are checking if favoriteitem
exists (which it never will because it is a brand new object you just created). I would suggest checking by some unique identifier. Without knowing too much about your project, I would suggest something like the following:
Assuming your link field is unique per favorite item, the following should help:
//this is your new created favoriteitem to check against
final favoriteitem = new FavoriteItem(headline: item['headline'], content: item['content'], link: item['link'], publisheddate: item['publisheddate']);
//find existing item per link criteria
var existingItem = items.firstWhere((itemToCheck) => itemToCheck.link == favoriteitem.link, orElse: () => null);
If existingItem
is null
, then nothing exists in your list that matches that link, otherwise it will return the first item matching that link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With