I am building a multiplayer game in Flutter using Firestore to handle real-time updates. One of the cases I need to address is when a player fully terminates the app. In this case, Firestore should be updated to remove the player from the active party.
I'm attempting to achieve this by using a Firebase Cloud Function that listens to the player’s presence status in Firebase Realtime Database. When the player’s presence changes to {online: false}, the Cloud Function updates Firestore and removes the player from the party.
The issue I’m facing is that I’m unable to reliably change the player’s status in Firebase Realtime Database when the app is fully terminated. I have the following method that I call whenever the app’s lifecycle state changes:
void updatePresenceOnAppState(
AppLifecycleState state,
String partyId,
String playerId,
) {
print(state);
final presenceRef = _database
.ref()
.child('party-presence')
.child(partyId)
.child(playerId);
if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
presenceRef.set({'online': true, 'state': 'background'});
} else if (state == AppLifecycleState.detached) {
presenceRef.set({'online': false, 'state': 'terminated'});
} else if (state == AppLifecycleState.resumed) {
presenceRef.set({'online': true, 'state': 'active'});
}
}
However, AppLifecycleState.detached does not seem to reliably set the online status to false upon app termination. This results in the player’s status remaining as "online" even after the app is closed.
Is there a reliable way to detect full app termination in Flutter to update the player’s presence status in Firebase Realtime Database? Or is there a recommended approach to handle player termination events to trigger the necessary Firestore updates?
I tried using AppLifecycleState.detached to detect when the app is fully terminated. My expectation was that setting {online: false, state: 'terminated'} in Firebase Realtime Database within AppLifecycleState.detached would reliably mark the player as offline, which would then trigger my Cloud Function to remove the player from the party in Firestore.
What actually happened:
Instead, AppLifecycleState.detached doesn’t seem to update the Firebase Realtime Database consistently when the app is terminated, leaving the player's status as "online" even after they close the app. This means the Cloud Function doesn’t run, and the player isn’t removed from the party as expected.