gpt4 book ai didi

dart - 如何在Dart中删除重复项

转载 作者:行者123 更新时间:2023-12-03 03:40:13 24 4
gpt4 key购买 nike

所以这是我设置数据的方式

  loadNotification(int limit, int offset) async {
List<Notification> notif =
await fetchNotification(http.Client(), limit, offset);
tempNotification.addAll(notif);

_notificationController.add(tempNotification);
}

这是我的 Notification()
class Notification {
final String notificationId;
final String notificationTitle;
final String notificationBody;
final String notificationDate;
final String notificationTo;
final String notificationImage;

Notification({
this.notificationId,
this.notificationTitle,
this.notificationBody,
this.notificationDate,
this.notificationTo,
this.notificationImage,
});

factory Notification.fromJson(Map<String, dynamic> json) {
return Notification(
notificationId: json['notificationId'] as String,
notificationTitle: json['notificationTitle'] as String,
notificationBody: json['notificationBody'] as String,
notificationDate: json['notificationDate'] as String,
notificationTo: json['notificationTo'] as String,
notificationImage: json['notificationImage'] as String);
}
}

因此,举个例子,我的第一个数据将显示1,2,3,4,5,然后单击“加载”,它将显示1,2,3,4,5,3,4,5,6,7。

我已经尝试将 loadNotification更改为此
  loadNotification(int limit, int offset) async {
List<Notification> notif =
await fetchNotification(http.Client(), limit, offset);
tempNotification.addAll(notif);
filteredNotification = tempNotification.toSet().toList();
_notificationController.add(filteredNotification);
}

但仍然没有帮助,我该如何实现?提前致谢

最佳答案

tempNotification.toSet().toList() 

不能按预期工作,因为必须重写Notification类的equals和hashCode,仅在这种情况下,您将按值进行比较,否则按ref进行比较。

一些基于notificationId的示例:
class Notification {
final String notificationId;
...
bool operator ==(o) => o is Notification && notificationId == o.notificationId;
int get hashCode => notificationId.hashCode;
}

关于dart - 如何在Dart中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57200260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com