我有一个名为动态类型的选定列表的列表,它包含一个对象列表,每个对象都包含教师 ID 和索引。
我想检查这个列表是否包含相同的 ID 和索引,如果是,我想从列表中删除这个对象。
这是我的代码......
void addTeacher(int teacherId, int index) {
if (this.selectedList.contains({ **/// the problem is here** })) {
this.selectedList.remove({teacherId, index});
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
this.selectedList.add({teacherId, index});
this.myColor = AsasColors().blue;
print('added teacher => ${teacherId.toString()}');
}
notifyListeners();
print(selectedList);
}
我怎样才能实现这个目标?
最佳答案
包含和删除使用 == 运算符,在这种情况下将返回 false,因为除非您为特定类重写它,否则它将通过引用进行比较。 您可以使用indexWhere 基于类似的比较函数来查找某个项目是否在列表中(如果该函数返回-1,则该项目不在列表中:
// Index different than -1 means the item is found somewhere in the list
final teacherIndex = this.selectedList.indexWhere((teacher) => teacher['teacherId'] == teacherId);
if (teacherIndex != -1) {
this.selectedList.removeAt(teacherIndex);
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
...
}
关于list - 如何从 dart/flutter 的列表中删除特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69415034/