Trouble changing status - Flutter [Firestore]

Viewed 53

I use Firestore to save the account status, when the account is active the value of the status field is changed to online and when he logs out of the account the status changes to offline. By sending an order to change the status.

But there are two problems!

First: When the account loses the internet connection, how to change the status to Offline?

Second: When the user close the application through the display button of the active applications on the device

How to solve these problems, note that I searched for a long time and did not find a logical solution.

1 Answers

The Firebase Realtime Database has native support to handle those two scenarios (users closing the app and internet connection issues).

You can, however, deploy a Cloud Function to reflect these status changes to Firestore, since Firestore by itself does not have this feature. You can refer to this guide which has a full walkthrough of how to implement the code.

The architecture can be summarized as follows:

  1. A special path in Realtime DB handles connection status between the client and server (/.info/connected). This returns a boolean and changes automatically.
  2. An onDisconnect() operation can be queued to the server which will automatically run when the connection is lost. This operation can be set up to update an RTDB reference (e.g. one that represents connection status for users through their uid status/{uid}).
  3. The Cloud Function can be set up to listen to changes at this status reference, and update the relevant Firestore document.
  4. All other devices that query this document will know of any user disconnecting.
  5. The client application can listen to /.info/connected, which is useful for updating the connection status back to online reference when users re-connect.

For your Flutter client code, you can also take a look at the specific Flutter documentation about user presence. Let me know if this was useful.

Related