I createad a class Question that extends equatable: it has a property named "answers" which is a List of String of dimension 4. I would like to compare 2 questions that have the same answers, whose items are unordered. Any ideas on how to do it? Overriding the props with [answers] is not enough... Thanks! Here is the question model:
@immutable
/// Question class to model the api response: it will be
/// used in the Presentation layer
class Question extends Equatable {
final String question;
final String correctAnswer;
final List<dynamic>? answers;
const Question({
required this.question,
required this.correctAnswer,
this.answers,
});
@override
List<Object?> get props => [
question,
correctAnswer,
answers,
];
then i create a QuestionModelResponse that extends the Question class (that represents the data that i want to visualize) that has a method toEntity() to convert it into a question:
@immutable
class QuestionResponseModel extends Question {
final List<dynamic> incorrectAnswers;
const QuestionResponseModel({
required correctAnswer,
required question,
required this.incorrectAnswers,
}) : super(
correctAnswer: correctAnswer,
question: question,
);
factory QuestionResponseModel.fromJson(Map<String, dynamic> map) {
return QuestionResponseModel(
question: map['question'] ?? '',
correctAnswer: map['correct_answer'] ?? '',
incorrectAnswers: map['incorrect_answers'] ?? [],
);
}
Question toEntity() {
return Question(
question: question,
correctAnswer: correctAnswer,
answers: incorrectAnswers
..add(correctAnswer)
..shuffle());
}
@override
List<Object?> get props => [
question,
correctAnswer,
incorrectAnswers,
];
}
and this is a sample of the json response:
{
"response_code": 0,
"results": [
{
"category": "Entertainment: Books",
"type": "multiple",
"difficulty": "medium",
"question": "What is the fourth book of the Old Testament?",
"correct_answer": "Numbers",
"incorrect_answers": [
"Genesis",
"Exodus",
"Leviticus"
]
},
}
CodePudding user response:
In Dart Set
are equal if the values are same even the objects are in different order.
In your case, you can convert List
into a Set
with toSet()
method while comparing two different lists.
listA.toSet() == listB.toSet()