首页 > 解决方案 > firebase_database 在线/离线状态

问题描述

在使用 firebase 和 flutter-fire firebase_database 插件时,我们如何确定我们的 Flutter 应用是在线还是离线?

这篇博文 ( https://firebase.googleblog.com/2013/06/how-to-build-presence-system.html ) 展示了在应用上线时使用 '.info/connected' 子节点获取事件/离线。然而,它似乎只在应用程序启动时触发一次,仅此而已。

我正在使用这个:

void initState() {
    super.initState();

    print('Setting up the connected handler');
    final amOnline = FirebaseDatabase.instance.reference().child('.info/connected');
    _amOnlineSubscription = amOnline.onValue.listen((Event event) {
      print('EVENT has occured');
    });
  }

也许有更好的方法来确定在线/离线状态?我想要做的是在设备离线时避免登录页面。然而,一旦它再次连接到 Firebase,就强制登录......

标签: flutter

解决方案


我在我的应用程序上使用connectivity_plus插件来检查应用程序是否有活动的网络连接。这样,您就不需要使用 firebase_database 来检查设备的连接性。

您可以将其添加到应用程序的 initState()

@override
initState() {
  super.initState();

  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // Check connectivity status
  })
}

并确保在完成后取消订阅。

@override
dispose() {
  super.dispose();

  subscription.cancel();
}

推荐阅读