The below code update the presence field to true upon losing the internet or when I clear the app from memory. When I press the back or home button, the presence field in the database remains to true. How can I update presence field to false when the user press the home or back button.
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Database {
final FirebaseAuth _auth = FirebaseAuth.instance;
updatePresence() async {
DatabaseReference ref =
FirebaseDatabase.instance.ref(_auth.currentUser!.uid);
FirebaseDatabase.instance.ref('.info/connected').onValue.listen((event) {
if (event.snapshot.value == false) {
return;
}
ref.onDisconnect().set({'presence': false}).then((value) {
ref.set({'presence': true});
});
});
}
}
Pressing the
backbutton does not close the connection to the database. Even if you exit the app, it may take a few minutes before the server detects that the client is gone and runs theonDisconnecthandler(s) that you registered.If you want to force the connection to be closed, you can call
goOffline()as also explained in the documentation on detecting connection state: