0

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});
      });
    });
  }
}
josef
  • 133
  • 2
  • 3
  • 8

1 Answers1

1

Pressing the back button 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 the onDisconnect handler(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:

On Android, Firebase automatically manages connection state to reduce bandwidth and battery usage. When a client has no active listeners, no pending write or onDisconnect operations, and is not explicitly disconnected by the goOffline method`, Firebase closes the connection after 60 seconds of inactivity.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807