颤振:检查列表中是否已存在对象

Wat*_*ame 5 dart flutter

我有以下代码

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经开始了这样的课程

final FavoriteList favlist = new FavoriteList();favlist用来自 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);
   });
 }
Run Code Online (Sandbox Code Playgroud)

问题

我想要做的是在添加之前检查对象是否favoriteitem已经存在favlist

我尝试使用 -

favlist.items.contains favlist.items.indexof 但没有用

我是扑扑/飞镖的新手,有人可以帮我吗

cal*_*pid 10

favlist.items.contains并且favlist.items.indexof不工作,因为我假设您正在检查是否favoriteitem存在(它永远不会因为它是您刚刚创建的全新对象)。我建议通过一些唯一标识符进行检查。在不太了解您的项目的情况下,我建议如下:

假设您的链接字段对于每个收藏项都是唯一的,以下内容应该会有所帮助:

//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);
Run Code Online (Sandbox Code Playgroud)

如果existingItemnull,则列表中不存在与该链接匹配的任何内容,否则它将返回与该链接匹配的第一个项目。


小智 5

试试这个,添加了两个方法,它 contains() 应该可以正常工作

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;
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is FavoriteItem &&
          runtimeType == other.runtimeType &&
          headline == other.headline &&
          content == other.content &&
          link == other.link &&
          publisheddate == other.publisheddate;

  @override
  int get hashCode => hashValues(headline, content, link, publisheddate);
}
Run Code Online (Sandbox Code Playgroud)


Pab*_*era 5

你可以这样做:

listB.addAll(listA.where((a) => listB.every((b) => a.id != b.id)));
Run Code Online (Sandbox Code Playgroud)