[DAT]-检查对象列表中是否存在值



我有一个名为QuizzAnswer的抽象类,还有一个扩展QuizzAnwer类的名为QuizzyAnswerMCQ的类。

abstract class QuizzAnswer extends Equatable {}
class QuizzAnswerMCQ extends QuizzAnswer {
String optionId;
bool isSelected;
QuizzAnswerMCQ({required this.optionId, required this.isSelected});
@override
List<Object?> get props => [optionId, isSelected];
Map<String, dynamic> toJson() => {
"option_id": optionId,
"is_selected": isSelected,
};
}

我有一个QuizzAnswerMCQ 类型的列表

List<QuizzAnswerMCQ> quizAnswerList=[];

我把项目添加到列表中

quizAnswerList.add(QuizzAnswerMCQ(
optionId: event.optionId, isSelected: event.optionValue));

我想做的是检查optionId是否已经在列表中,所以我写了这个,

if(quizAnswerList.map((item) => item.optionId).contains(event.optionId)){
print ('EXISTTTTSSSSS');
}else{
print('DOESNT EXISTTTT');
}

即使optionId在那里,我仍然得到输出"DOESNT EXISTTTT"。请帮忙!!!

执行此

if (quizAnswerList
.where((element) => element.optionId == event.optionId)
.isNotEmpty) {
print ('EXISTTTTSSSSS');
}
else{  print('DOESNT EXISTTTT'); }

.where((方法检查并创建一个列表,因此如果它不为空,则该项目存在

您可以像这个一样使用firstWhere

result = quizAnswerList.firstWhere((item) => item.optionId == your_id);

或从其他列表进行检查

result = quizAnswerList.firstWhere((item) => otherList.contains(item));

然后

if(result.length > 0){
print ('');
}else{
print(');
}

此处为官方文档

最新更新