如何在Dart中删除重复项

时间:2019-07-25 10:51:46

标签: dart

这就是我设置数据的方式

  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。 / p>

我已经尝试将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);
  }

但仍然没有帮助,我该如何实现?预先感谢

2 个答案:

答案 0 :(得分:1)

pro

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

一些基于notificationId的示例:

tempNotification.toSet().toList() 

答案 1 :(得分:0)

最简单的方法是使用地图,因为地图仅包含唯一性。像这样:

Map<String, Notification> notificationsMap = {}

if(!notificationsMap.containsKey(notification.id)){
 notificationsMap[notification.id] = notification;
}

--

In your example:
// please write out the whole name, it gets confusion otherwise

List<Notification> notifications = await fetchNotification(http.Client(), limit, offset);

notifications.forEach((Notification notification){
  if(!notificationsMap.containsKey(notification.id)){
    notificationsMap[notification.id] = notification;
  }
});

-> now you can access all notifications by e.g. calling:

notificationsMap.keys.toList();