flutter - 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,就强制登录......
解决方案
我在我的应用程序上使用connectivity_plus插件来检查应用程序是否有活动的网络连接。这样,您就不需要使用 firebase_database 来检查设备的连接性。
您可以将其添加到应用程序的 initState()
@override
initState() {
super.initState();
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Check connectivity status
})
}
并确保在完成后取消订阅。
@override
dispose() {
super.dispose();
subscription.cancel();
}
推荐阅读
- ansible - 运行ansible playbook时遇到“无法访问”“权限被拒绝”错误
- java - 在 Eclipse 中使用正则表达式在 xml 文件中查找查询
- python - 为什么每个线程都得到一个新的 packageManager 对象副本?我怎么可以只用一个?
- azure-devops - ADO 项目的存档选项
- android - 在 Android 上的 NavigationButton 中将大小设置为图标
- java - WebClient 请求级别超时抛出称为默认 onErrorDropped 的运算符
- php - 转化上传:如何在每次转化上传时设置转化窗口?
- javascript - 从反应原生组件调用javascript函数
- amazon-web-services - 使用 Terraform 创建 AWS 服务角色
- android - react-native-firebase 自定义声音在 android 8、android 9 上不起作用