Как удалить повторяющийся элемент в 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);
  }

но все равно не помогает, как я могу этого добиться? заранее спасибо

1
0
365
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Самый простой способ — использовать карту, потому что карта содержит только уникальные объекты. Как это:

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();

Ответ принят как подходящий
tempNotification.toSet().toList() 

Не работает так, как вы ожидаете, потому что вам нужно переопределить equals и hashCode для класса Notification, только в этом случае вы будете сравнивать по значению, иначе по ссылке

Некоторый пример на основе уведомленияId:

class Notification {
  final String notificationId;
  ...
  bool operator ==(o) => o is Notification && notificationId == o.notificationId;
  int get hashCode => notificationId.hashCode;
}

можете ли вы показать мне, как это реализовать? я немного запутался

Boby 26.07.2019 05:25

Другие вопросы по теме