在颤振中从列表中添加和删除对象



我有一个名为selectedList的动态类型的列表,它应该包含一个对象列表。每个对象由teacherId和subjid组成,像这样[{1,2},{4,9},{7,3}…]等)

我想要实现的是我可以删除和添加对象到这个列表,如果对象存在,它应该被删除,如果它不存在,它应该被添加。

我尝试了包含方法,但它没有工作!

添加方法

List<dynamic> selectedList = [];
void addTeacher(Teachers teacherId, Subjectt subjectId) {
if (this.selectedList.contains({  *** this method is not working***     })) {
this.selectedList.remove({teacherId, subjectId});
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
this.selectedList.add({teacherId, subjectId});
this.myColor = AsasColors().blue;
print('added teacher => ${teacherId.toString()}');
}
notifyListeners();
print(selectedList);}

我调用方法

ListTile(

onTap:() {card.addTeacher (e,cardData.subjects [subjectIndex]);},

leading: CircleAvatar(
backgroundColor:
AsasColors().white,
backgroundImage:
NetworkImage(
e.profilePicture),
),
title: MediumRegularFont(
string: e.name,
),),

请帮助我真的厌倦了这个问题!

正如您提到的Object,由于contains方法不起作用

...
if (this.selectedList.contains({  *** this method is not working***     })) ...
步骤1

我想你是在使用包含对象而不覆盖它们的哈希码和相等操作符

,

class Teacher {
String id;
String name;
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;

return other is Teacher &&
other.id == id;
}
@override
int get hashCode => id.hashCode;
}
步骤2

由于您在列表中使用Set,您必须以不同的方式比较它们

也去掉this关键字,不一定是

List<Set> selectedList = [];
void addTeacher(Teachers teacherId, Subjectt subjectId) {
if (selectedList.indexWhere((element) => 
element.first == teacherId && element.last == subjectId)) != -1 ) {
selectedList.remove({teacherId, subjectId});
myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
selectedList.add({teacherId, subjectId});
myColor = AsasColors().blue;
print('added teacher => ${teacherId.toString()}');
}
notifyListeners();
print(selectedList);
}

List().indexWhere方法将返回-1如果元素没有在列表中找到。你也可以使用其他方法,比如List().every

(为了代码的可读性和降低复杂性,我建议您使用Map而不是Set)

相关内容

  • 没有找到相关文章

最新更新