借助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
}