I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().
class MyClubController extends GetxController {
List goldLane = List.filled(3, null, growable: false);
void _alterLanesOnContractEnds() {
for (var i in goldLane) {
print("\n\n I: $i");
if (i == null ||
DateTime.parse(i['contractEnds']).isBefore(
DateTime.now(),
)) {
i = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
}
CodePudding user response:
A for-in
loop will not allow you to reassign elements of the List
. When you do:
for (var i in goldLane) {
// ...
i = null;
}
you are reassigning what the local i
variable refers to, not mutating the goldLane
List
.
You instead can iterate with an index:
void _alterLanesOnContractEnds() {
for (var i = 0; i < goldLane.length; i = 1) {
var element = goldLane[i];
print("\n\n I: $element");
if (element == null ||
DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)) {
goldLane[i] = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
CodePudding user response:
You can just create a new List
with qualified guests. For example,
void _alterLanesOnContractEnds() {
goldLane = goldLane.where((guest) => guest != null && !DateTime.parse(guest['contractEnds']).isBefore(DateTime.now())).toList();
update();
}
You should not and cannot modify a list while iterating with its iterator.