'[DART]- Check if a value exists in a list of objects
I've got an Abstract class named QuizzAnswer and I've a class named QuizzAnswerMCQ which extends QuizzAnswer class.
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,
};
}
and I've got a list which is of type QuizzAnswerMCQ
List<QuizzAnswerMCQ> quizAnswerList=[];
and I add items to the list
quizAnswerList.add(QuizzAnswerMCQ(
optionId: event.optionId, isSelected: event.optionValue));
what I want to do is to check if the optionId is already there in the list or not so I wrote this,
if(quizAnswerList.map((item) => item.optionId).contains(event.optionId)){
print ('EXISTTTTSSSSS');
}else{
print('DOESNT EXISTTTT');
}
Even though the optionId is there,I still get the output 'DOESNT EXISTTTT'.Please help!!!
Solution 1:[1]
You can use firstWhere like this
result = quizAnswerList.firstWhere((item) => item.optionId == your_id);
or checking from other List
result = quizAnswerList.firstWhere((item) => otherList.contains(item));
then
if(result.length > 0){
print ('');
}else{
print(');
}
Official doc here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhi Tripathi |
