Asad Malik
Asad Malik

Reputation: 3426

How I can get current active users from Firebase with Flutter?

I am making an application using flutter and firebase. I need to get active users from firebase. I am trying by creating a boolean field in firebase collection with name isActive = false and initiate a function with name _checkInternetConnectivity(); in this function I set when the internet connection is available update value of isActive = true in firebase and when there is no internet connection update value isActive = false so far my code is working perfectly but problem is that when internet connection is available it set the value of isActive = true but when there is no internet connection it unable to update the value isActive = false.
code is here:

void initState() {
    super.initState();
    _checkInternetConnectivity();
}

_checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': true,
      });
      print('done mobile');
    } else if (connectivityResult == ConnectivityResult.wifi) {
      _addData.doc(user.uid).update({
        'isActive': true,
      });
      print('done wifi');
    } else if (connectivityResult == ConnectivityResult.none) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': false,
      });
      print('done none');
    }
  }
}

so, how I can improve this code or any other way by which I can get active users from firebase with flutter.

Regards

Upvotes: 9

Views: 1149

Answers (2)

Edwin Liu
Edwin Liu

Reputation: 8025

You can create a field like lastActiveTimestamp and update it every time an user opens the app. Then you can filter users by the last time they use the app.

Upvotes: 0

Kamal Nayan
Kamal Nayan

Reputation: 1718

OnDisconnect

The OnDisconnect class is used to manage operations that will be run on the server when this client disconnects. It can be used to add or remove data based on a client's connection status. It is very useful in applications looking for 'presence' functionality.

Instances of this class are obtained by calling onDisconnect on a Firebase Database ref.

Your solution is here

Upvotes: 1

Related Questions