list - 如何从 dart/flutter 的列表中删除特定对象?

标签 list flutter dart

我有一个名为动态类型的选定列表的列表,它包含一个对象列表,每个对象都包含教师 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/

相关文章:

python - 转换二叉树中的嵌套列表的列表

list - Lisp 格式程序

python - 在列表 python 中查找包含 0-23 中所有值的列表

flutter - 如何修复 'NoSuchMethodError: The getter ' 长度' was called on null'

firebase - 如何将 Future 变量分配给 Flutter 中的类 getter

html - 为什么它在没有 overflow hidden 的情况下不起作用?

android - Flutter 应用程序中 firebase 数据库上的 ValueEventListener

Flutter - Locale 的可空性问题

android - 任务 ':app:processDebugResources' 的 Flutter 执行失败。 AAPT : error: resource string/app_name not found

dart - Flutter-如何打开手机图库?