I'm getting infinite loop when I call setstate function in the stateful widget in the below code.
When I remove it, it stops the loop but then I won't get my widget updated so I need to use setstate to update my widget but I can't find a way out of this infinite loop it is causing.
//On changes in players reference in the RT DB
playersRef.onValue.listen(
(DatabaseEvent event) {
print("Changes in DB");
List<Player> tempPlayers = [];
for (final playerSnapshot in event.snapshot.children) {
//Adding all players info from RT DB into tempPlayers
tempPlayers.add(Player(
playerSnapshot.child("name").value.toString(),
playerSnapshot.child("id").value.toString(),
(judge == playerSnapshot.child("name").value.toString())
? true
: false,
playerSnapshot.child("isJudge").value as bool,
playerSnapshot.child("isLoaded").value as bool,
));
}
//Updating players list with tempPlayers list
setState(
() {
print("In set state");
players = tempPlayers;
},
);
},
);
I tried to remove setstate in different positions inside playersRef.onValue.listen() but none worked.
What Im trying to do with this part of code is to update my players list whenever there are any changes in the real time database then update my widget by using setstate to reflect the updated players list.