How to compare two lists of models and merge values of answers into one in Dart/Flutter?

class Questions {
  dynamic id;
  final String label;
  final String description;
  String answerText;

  Questions({
    this.id,
    this.label,
    this.description,
    this.answerText,
  });

 List<Questions> q1 = [Question(1, 'This is question 1', 'first_question',''), Question(2, 'This is question 2','second_question',''),Question(3, 'This is question 3', 'third',''), Question(4, 'This is question 4', 'fourth',''),Question(5, 'This is question 5', 'fifth',''), Question(6, 'This is question 6', 'sixth','')]; 

 List<Questions> q2 = [Question(1,'answer for question 1'), Question(3,'answer for question 3'), Question(5,'answer for question 5')];


Solution 1: Gursewak Singh

Use darq package, there are set operations with the except, intersect, and union methods.

Example

var listA = [1, 2, 3, 4];
var listB = [3, 4, 5, 6];

var exclusion = listA.except(listB);       // [1, 2]
var intersection = listA.intersect(listB); // [3, 4]
var union = listA.union(listB);            // [1, 2, 3, 4, 5, 6]


Solution 2: Thierry

I suppose you want to incorporate the answers within the questions, like this:

1: This is question 1
Desc: first_question
Answer:answer for question 1

2: This is question 2
Desc: second_question
Answer:Missing answer

3: This is question 3
Desc: third
Answer:answer for question 3

4: This is question 4
Desc: fourth
Answer:Missing answer

5: This is question 5
Desc: fifth
Answer:answer for question 5

6: This is question 6
Desc: sixth
Answer:Missing answer

Here is a solution using map on the List of Question:

void main() {
  List<Question> combined = questions
      .map((question) => question
          ..answerText =
            answers.firstWhere((answer) => answer.id == question.id, orElse: () => null)?.answerText ?? 'Missing answer')
      .toList();
  combined.forEach((question) => print(question));
}

class Question {
  dynamic id;
  final String label;
  final String description;
  String answerText;

  Question({
    this.id,
    this.label,
    this.description,
    this.answerText,
  });

  toString() => '$id: $label\nDesc: $description\nAnswer:$answerText\n';
}

List<Question> questions = [
  Question(id: 1, label: 'This is question 1', description: 'first_question'),
  Question(id: 2, label: 'This is question 2', description: 'second_question'),
  Question(id: 3, label: 'This is question 3', description: 'third'),
  Question(id: 4, label: 'This is question 4', description: 'fourth'),
  Question(id: 5, label: 'This is question 5', description: 'fifth'),
  Question(id: 6, label: 'This is question 6', description: 'sixth'),
];

List<Question> answers = [
  Question(id: 1, answerText: 'answer for question 1'),
  Question(id: 3, answerText: 'answer for question 3'),
  Question(id: 5, answerText: 'answer for question 5'),
];