首页 > 解决方案 > 如何在 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。

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

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

标签: dart

解决方案


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

推荐阅读