firebase - 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);
}
}
});
});
}
});}
我提前感谢您的帮助!
解决方案
经过1个月的尝试,我终于解决了。 答案:
@override bool operator ==(other) {
return (other is Group)
&& other.id == id; }
我需要这样做,以便 Flutter 明白,如果两个组的 ID 相同,则它们是相同的。
推荐阅读
- ios - UIPIckerViews 在一个 UIView 中协同工作
- amazon-web-services - AWS SOA-C01 考试准备:私有 VPC
- sql - Oracle SQL Left Join 与 FROM 中的多个表
- azure-api-management - 在 vnet 部署的 API 管理实例中导入私有 API 应用(Azure 应用服务)作为 API
- blazor - 缺少 Blazor WebAssembly 3.1 目标框架
- react-native - 如何在 React Native 中处理 Seprate 文件中的导航
- firebase-cloud-messaging - 用户上线时的 Mqtt 消息传递
- android - 如何在android studio中使用ffmpeg添加像tic tok这样的水印
- javascript - 函数的空间复杂度
- javascript - 如何使用 api 在 reactjs 中添加搜索功能