我有一個地圖(radioValue),其中包含問題 id 和答案值的串列,還answerTable包含很多答案物件。觸發提交按鈕時,我想比較radioValueid 和 answerTable。如果 answerTable 中存在 radioValue 中的 id,則呼叫 edit api ,否則呼叫 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
}
}
}
}
我想出了這個代碼,但它是錯誤的。如果 answerTable 為空,則不會呼叫兩個 api。
最新代碼
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
}
}
錯誤
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)
uj5u.com熱心網友回復:
假設Answer模型是這樣的:
class Answer {
String answerId;
String questionId;
Answer({this.answerId, this.questionId});
}
名單是:
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'),
];
那么檢查可以是:
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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339432.html
