将 hashMap 值与列表项进行比较

Compare hashMap value with List item

我有一张地图,名为finalMap

var finalMap = Map<String, String>();

它包含问题 ID 和答案。

The output is {17: W, 19: N, 83: yes}

我还有一个answerTable列表,名字叫answerTable(List)

[ChecklistAnswerItem(id: 142, sectionItemId: 17, checklistsectionItem: Instance of 'ChecklistAnswerSectionItem', inputAnswer: W)]

我想要实现的是,如果映射 keyanswerTable.sectionItemId 中退出,它调用编辑 api,否则调用创建 api.

 Future editChecklistAnswer(
      String id, String checklistAnswerId, Map<String, String> textMap) async {

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

           ..
    print(finalMap);
    print(answerTable);

    for (final entry in finalMap.entries) {
      if (answerTable.isEmpty) {
        print("submit" + entry.key.toString());
       // I have my create api here
      } else {
        for (var i in answerTable) {
          if (entry.key.toString() == i.sectionItemId.toString()) {
            print("edit " + entry.key.toString());
           // I have edit api here
          } else {
            print("create " + entry.key.toString());
           // I have create api here
          }
        }
      }
    }
  }

但是我得到了一个奇怪的结果。起初我可以在 answerTable 长度为空时调用创建 api。但是当我去编辑它时,它会在调用 edit api 之后调用 create api..这里有什么问题?

输出

{17: T, 16: v}
[]
submit 17
submit 16
{17:  T, 16: 123}
[ChecklistAnswerItem(id: 388, sectionItemId: 17, checklistsectionItem: Instance of 'ChecklistAnswerSectionItem', inputAnswer: W), ChecklistAnswerItem(id: 389, sectionItemId: 16, checklistsectionItem: Instance of 'ChecklistAnswerSectionItem', inputAnswer: 123)]
edit 17
create 17   // it suppost not to call create api!!!
create 16  // it suppost not to call create api!!!

像这样的事情你可以做到,这不是 100% 的解决方案,但你可以解决它。我已经模拟了你可以使用 release 类 和 variables

    void checkForAction() {
      // Check list but sending ID you want
      editChecklistAnswer(finalMap.keys.first);
    }

    Future editChecklistAnswer(int checklistAnswerId) async {
      List<ChecklistAnswerItem> answerTable = answerTableList;
      if (answerTable.isEmpty) {
        //TODO:Submit
      }
      bool isAnswerExist = answerTable
          .where((element) => element.sectionItemId == checklistAnswerId)
          .isNotEmpty;
      if (isAnswerExist) {
        //TODO: Call Edit API
      } else {
        //TODO: Call crease API
      }
    }

    final Map<int, String> finalMap = {1: 'W', 2: 'N', 3: 'Yes'};

    final answerTableList = [
      ChecklistAnswerItem(1),
      ChecklistAnswerItem(2),
      ChecklistAnswerItem(3),
    ];

    class ChecklistAnswerItem {
      final int sectionItemId;

      ChecklistAnswerItem(this.sectionItemId);
    }