借助Flutter和Firebase实现实时的在线/离线状态 [英] Implement realtime online/offline status with flutter and firebase

查看:72
本文介绍了借助Flutter和Firebase实现实时的在线/离线状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,如果用户在线或离线,在应用中显示的最佳方式是什么?

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

前端->颤振

后端-> Firestore云和Firebase身份验证.

Backend -> Firestore Cloud and Firebase Auth.

我在Firestore中有一个包含文档的用户集合.每个文档都是用户,并且包含状态"字段.很快,我可以在用户每次登录或注销时更新此字段,但是如果您关闭该应用程序,则该字段不会更新.

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.

推荐答案

您可以使用 WidgetsBindingObserver 扩展statefulWidget State类像

You can extend your statefulWidget State class with WidgetsBindingObserver like

class _HomePageState extends State<HomePage>
    with WidgetsBindingObserver

initState 方法添加 WidgetsBinding.instance.addObserver(this); .

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

稍后覆盖 didChangeAppLifecycleState 方法

@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
  }

这篇关于借助Flutter和Firebase实现实时的在线/离线状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆