is it reliable, if i used to check in a list using any before going with foreach in the below example?
Just wondering to check is there any object has isSelected value as true, if so then do a foreach to add the particular object in another list. Is this good way to prevent the foreach or still directly do foreach without any. Because inside the any i can see they do the same foreach. Experts please advice.
final isAnyMainGod = listMainGod.any((element) => element.isSelected);
if (isAnyMainGod) {
listMainGod.forEach((element) {
if (element.isSelected) {
_tempID.add(
FilterData(type: 'MAINGOD', filterValue: element.mainGodNameId));
}
});
}
The issue I see here is that you are doing a potential full iteration of the list, followed up by another full iteration of the list, applying identical logic a second time.
You could do something like this:
var _tempId = listMainGod.where((element) => element.isSelected)
.map((e) => FilterData(type: 'MAINGOD', filterValue: e.mainGodNameId))
.toList();
In the my suggestion, the condition in the where
will remove any elements from the list, that don't evaluate to a true. There is still a full iteration of the list (but you'll have to do that anyway at some point), but this suggestion only has 1 full iteration, and a single line of code for the condition (as opposed to your two occurrences of element.isSelected
).
Then, the map, is an iteration on only the matching list items, to apply give to the FilterData
function.
In the event that no matching elements are found, you are provided a list with 0 elements.
The other added benefit of writing something like this, is it requires less cognitive load, to follow. You don't to know or care if isAnyMainGod
exists (or if you have to look and see if it's used elsewhere, because that one spot), you just iterate over any results you have from the result. In my experience, the fewer variables you use to track state results fewer potential places you can introduce bugs.