首页 > 解决方案 > Flutter - 从数组中删除重复项

问题描述

底线:如何从 firebase 数据库中检索数据、插入数组并刷新列表视图而不获取重复项?

我正在从 Firebase 数据库获取数据并将其加载到颤振应用程序中的数组中。然后,我使用 Listview.Builder 制作数组项的列表。

问题是当我刷新页面(使用刷新包)时,列表中的项目会重复。它们从 firebase 加载并再次加载到阵列上。

我尝试使用array.contains(element.id)(因为每个项目都有一个唯一的 ID)有条件地将项目插入到数组中,如果它不存在的话。

然而,这个条件总是错误的,尽管数组中的 ID 是相同的(我打印出来检查)。我怎样才能使这种情况或类似情况起作用?

检查重复的功能:

bool isDuplicate(Group group) {
bool result = false;
if (groupList.contains(group.id)) {
  result = true;
} else {
  result = false;
}
return result;}

从数据库中获取项目的功能:

Future searchGroupsDB() async {
return await userGroupsRef.once().then((snapshot1) {
  Map<dynamic, dynamic>? groupTitles = snapshot1.value;
  if (groupTitles != null) {
    groupTitles.forEach((key, value1) {
      userGroupsRef.child(key).once().then((snapshot2) {
        String? title = snapshot2.key;
        String id = snapshot2.value["ID"];
        String colors = snapshot2.value["Colors"];
        String description = snapshot2.value["Description"];
        if (snapshot2.value != null) {
          Group groupToInsert = Group(
              id: id,
              title: title!,
              description: description,
              containsImage: (displayImage != null) ? true : false,
              color: GradientColors.black,
              textColor: Colors.white);
          if (isDuplicate(groupToInsert) == true) {
            print("group already exists"); //this is never printed
          } else if (isDuplicate(groupToInsert) == false){
           groupList.insert(0, groupToInsert);
          }
        }
      });
    });
  }
});}

我提前感谢您的帮助!

标签: firebaseflutterdartfirebase-realtime-database

解决方案


经过1个月的尝试,我终于解决了。 答案

@override bool operator ==(other) {
return (other is Group)
    && other.id == id; }

我需要这样做,以便 Flutter 明白,如果两个组的 ID 相同,则它们是相同的。


推荐阅读