1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Firebase Realtime Database .info/connected listener always says "false." (Flutter)

Discussão em 'Mobile' iniciado por Stack, Outubro 22, 2024 às 04:13.

  1. Stack

    Stack Membro Participativo

    In a Flutter/Firebase app, I am trying to have a way of tracking whether users are "online" or not (for purposes of having a directory filterable by "is Online", for exmaple).

    At the point in the app where the uid becomes known, I added this:

    void _setUpPresenceListener(String uid) async {

    // *** Un-used Realtime Database reference to keep the connection alive
    DatabaseReference userStatusRef = FirebaseDatabase.instance.ref('status/$uid');

    // Reference to the .info/connected node in Realtime Database
    DatabaseReference connectedRef = FirebaseDatabase.instance.ref(".info/connected");

    // Firestore reference to the users_presence collection
    DocumentReference presenceRef = FirebaseFirestore.instance.collection('users_presence').doc(uid);

    // Listen for connection state changes
    connectedRef.onValue.listen((event) async {
    final bool isConnected = event.snapshot.value as bool? ?? false;

    // ***
    print("&&& - val: ${event.snapshot.value.toString()}");

    // If connected, set isOnline to true in Firestore
    if (isConnected) {

    await presenceRef.set({
    'isOnline': true,
    'lastChanged': FieldValue.serverTimestamp(),
    });
    } else {
    // When disconnected, set isOnline to false
    await presenceRef.set({
    'isOnline': false,
    'lastChanged': FieldValue.serverTimestamp(),
    });
    }
    });
    }


    This resulted in the firestore data field always being set to false, so I investigated/troubleshooted(?) by adding the parts marked *** which further verified the issue -- printed value is explicit 'false'

    Important points:

    • Security Rules are not an issue since the field is being written to successfully.
    • I am testing with an android emulator.
    • I am not using realtime database for any other purpose in the app.

    Is there some other pre-requisite to this listener refecting an accurate connection state?

    I was considering whether the reason may be that I am not using realtime database for anything else... and so maybe .info/... is never initialized to anything meaningful because of this?

    Continue reading...

Compartilhe esta Página