dune98
dune98

Reputation: 177

Implement realtime online/offline status with flutter and firebase

what is the best way to show in an app if the user is online or offline?

Frontend -> Flutter

Backend -> Firestore Cloud and Firebase Auth.

I have a collection of users in Firestore that contains documents. Each document is a user and contain status field. In Flutter, I can update this field every time that user log in or log out but if you close the app it is not updated.

Upvotes: 12

Views: 11965

Answers (3)

Tisanthan
Tisanthan

Reputation: 33

You can catch in onerror.

You have to chenge souce as server source: Source.server

users.get(GetOptions(source: Source.server))

final FirebaseFirestore _firestore = FirebaseFirestore.instance;
      final CollectionReference users = _firestore.collection('users');
    
      users.get(GetOptions(source: Source.server))
          .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
          print(doc["first_name"]);
          print(doc["last_name"]);
          print(doc["gender"]);
          print(doc["phone_number"]);
        });
      }).onError((error, stackTrace) {
        print(error.toString());//Offline
        Global.showSnackBar(context, error.toString(), false);
      });

Upvotes: 1

Shadeer
Shadeer

Reputation: 89

IT CAN DONE BY WidgetsBindingObserver();

class _HomeState extends State<Home> with WidgetsBindingObserver {...}

initialize it first

@override
void initState() {
super.initState();
WidgetsBinding.instance!.addObserver(this);
}

After add this function to listen for app state didChangeAppLifecycleState()

String? changes;

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);

final isBg = state == AppLifecycleState.paused;
final isClosed = state == AppLifecycleState.detached;
final isScreen = state == AppLifecycleState.resumed;

isBg || isScreen == true || isClosed == false
    ? setState(() {
      // SET ONLINE
    })
    : setState(() {
      //SET  OFFLINE

    });
print('CHANGES IS : $changes ');

}

String? changes Contains Your app State! Be Happy You Can what you want , This can notify Online status like Whatsapp Messenger!

MyCode :

    isBg || isScreen == true || isClosed == false
    ? setState(() {
      changes = "User is online"
    })
    : setState(() {
      changes = "User is Offline"
    });
    print('CHANGES IS : $changes ');

Upvotes: 2

Harsha pulikollu
Harsha pulikollu

Reputation: 2436

You can extend your statefulWidget State class with WidgetsBindingObserver like

class _HomePageState extends State<HomePage>
    with WidgetsBindingObserver

and initState method add WidgetsBinding.instance.addObserver(this);.

@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

Later overide didChangeAppLifecycleState method

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed)
      //TODO: set status to online here in firestore
    else
      //TODO: set status to offline here in firestore
  }

Upvotes: 23

Related Questions