Home > OS >  compare items in Map and List
compare items in Map and List

Time:10-28

I have a map(radioValue) which holds list of question id, and answer value, also a answerTable holds lot of Answer Object.When submit button triggered, I would like to compare radioValue id and answerTable. If id in radioValue exists in answerTable, call edit api , otherwise call edit api

List<ChecklistAnswerItem> answerTable =
        await _repository.selectChecklistAnswerItemsList();

    for (var key in radioValue.keys) {
      if (radioValue[key] != "") {
        for (var i in answerTable) {
          if (key == i.sectionItemId) { 
            // if key(question id) same with i.sectionItemId(answer id)
            // call edit api
          } else {
            // call create api
          }
        }
      }
    }

I came out with this code, but it is wrong. If answerTable is empty, both api will not be called.

Latest code

for (var key in radioValue.keys) {
      if (radioValue[key] != "") {
        var answer =
            answerTable.firstWhere((a) => a.checklistsectionItem?.id == key);
        print(answer);
        //call create api
      } else {
       //call edit api
       }
    }

Error

E/flutter (27156): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: No element
E/flutter (27156): #0      ListMixin.firstWhere (dart:collection/list.dart:167:5)

CodePudding user response:

Assuming the Answer model is this:

class Answer {
  String answerId;
  String questionId;
  Answer({this.answerId, this.questionId});
}

And the lists are:

List<String> questionIds = ['1', '2', '3', '4'];
List<Answer> answerIds = [
  Answer(answerId: '1', questionId: '1'),
  Answer(answerId: '73', questionId: '3'),
  Answer(answerId: '43', questionId: '3'),
  Answer(answerId: '123', questionId: '14'),
  Answer(answerId: '322', questionId: '88'),
  Answer(answerId: '13', questionId: '123'),
  Answer(answerId: '32', questionId: '355'),
];

then the checks can be:

void checkLists() {
  var specificQuestionId = '1';
  // This checks if there are any question IDs in answers list
  if (answerIds.any((a) => questionIds.contains(a.questionId))) {
    print('Yes there are question ids in answers list');
  }
  // This checks if there is a specific ID in answers list
  if (answerIds.any((a) => a.questionId == specificQuestionId)) {
    print('Yes the question id is in answers list');
    // if you want to get the value of the answer you can use firstWhere
    var answer = answerIds.firstWhere((a) => a.questionId == specificQuestionId);
  }
}
  • Related