Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement realtime online/offline status with flutter and firebase

Hy, 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 sign in or log out but if you close the app it is not updated.

like image 925
dune98 Avatar asked Mar 21 '20 05:03

dune98


1 Answers

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
  }
like image 91
Harsha pulikollu Avatar answered Sep 23 '22 17:09

Harsha pulikollu