[英]How to remove if-else chain from Dart?
我在 Flutter 應用程序中有一個相當大的 if-else 鏈,它從標題列表中檢查一堆條件。 我試圖弄清楚如何在沒有這一系列 if-else 語句的情況下處理這樣的鏈。 Map 是否合適,或者可能是一個簡單的開關盒?
if (listOfMaps[i]["title"] == "BPM LOW" && !activeAlarms.contains("BPM LOW")) {
activeAlarms.add("BPM LOW");
} else if (listOfMaps[i]["title"] == "BPM HIGH" && !activeAlarms.contains("BPM HIGH")) {
activeAlarms.add("BPM HIGH");
} else if (listOfMaps[i]["title"] == "PIP LOW" &&
!activeAlarms.contains("PIP LOW")) {
activeAlarms.add("PIP LOW");
} else if (listOfMaps[i]["title"] == "PIP HIGH" &&
!activeAlarms.contains("PIP HIGH")) {
activeAlarms.add("PIP HIGH");
}
for (final data in listOfMaps) {
final title = data["title"];
if (!activeAlarms.contains(title)) {
activeAlarms.add(title);
}
}
List activeAlarms = ["BPM HIGH"];
List listOfMaps = [
{"title": "BPM LOW"},
{"title": "BPM HIGH"},
{"title": "PIP LOW"},
{"title": "PIP HIGH"},
];
print('listOfMaps:');
print(listOfMaps);
print('activeAlarms before:');
print(activeAlarms);
listOfMaps.forEach((e) {
activeAlarms.singleWhere((element) => (element == e["title"]), orElse: () {
activeAlarms.add(e["title"]);
});
});
print('activeAlarms after:');
print(activeAlarms);
這是一些代碼。
和 output:
flutter: listOfMaps:
flutter: [{title: BPM LOW}, {title: BPM HIGH}, {title: PIP LOW}, {title: PIP HIGH}]
flutter: activeAlarms before:
flutter: [BPM HIGH]
flutter: activeAlarms after:
flutter: [BPM HIGH, BPM LOW, PIP LOW, PIP HIGH]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.