[英]How to remove if-else chain from Dart?
I have quite a huge if-else chain in a Flutter application which checks a bunch of conditions from a list of titles.我在 Flutter 应用程序中有一个相当大的 if-else 链,它从标题列表中检查一堆条件。 I'm trying to figure out how to deal with such a chain without this series of if-else statements.我试图弄清楚如何在没有这一系列 if-else 语句的情况下处理这样的链。 Would a Map be suitable, or maybe a simple switch case? 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);
Here's some code.这是一些代码。
And output:和 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.