How can I remove a node from a firebase realtime database when the app exits
When my app crashes or the user closes the app I want a particular node to be deleted from the
real-time database.
So, far I am not able to find any way to handle this issue. Could you please point out any reference material or anything of value that can help me implement this? Here I want the availableDrivers
to be removed but for that, I need to find the state of the app, how is it done? I want to do this from the app itself and not from the functions that firebase / google services (cloud functions etc..)
The scenarios of the app can be like
-
minimized
-
force closed
-
phone dies
-
no internet etc..
Solution 1:
What you're describing is the purpose of Firebase's onDisconnect
method. This this method you can register an operation while you are connected to the database backend, which is then executed once the backend notices that the connection is gone.
A simple example:
// Somewhere in your application, trigger that the user is online:
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123/status");
await ref.set(true);
// And after;
// Create an OnDisconnect instance for your ref and set to false,
// the Firebase backend will then only set the value on your ref to false
// when your client goes offline.
OnDisconnect onDisconnect = ref.onDisconnect();
await onDisconnect.set(false);
The onDisconnect
can be triggered either through a clean disconnect, where the client informs the server it is about to disconnect, or through a dirty disconnect, where the client simply stops communicating with the server (for example in the case of a crash, or an actual loss of the physical connection). In the latter case, it may take up to a few minutes before the server detects that the client is gone, and thus runs the onDisconnect
handlers for that client.
Also see the FlutterFire documentation on offline capabilities.