Flutter / Firebase实时数据库-处理网络错误

问题描述

Firebase实时数据库插件https://pub.dev/packages/firebase_database

我的从数据库获取值的代码

DataSnapshot d = await database.reference().child("my/child/node").once();
Map map = d.value;
String val1 = map["val1"];
String val2 = map["val2"];
String val3 = map["val3"];

有效。但是,当没有网络连接时,它会无休止地等待。我想捕获错误(无法连接到数据库)。我该怎么办?尝试/捕获不起作用,因为没有引发异常,它只是等待。我想知道有关数据库连接错误的信息。有可能吗?

解决方法

您可以使用类似这样的调子:

 if (await database
      .reference()
.child("my/child/node")
    .once()
    .timeout(Duration(seconds: 5),onTimeout: () {
print('Spent 5 seconds and no connection');
}).isNotEmpty) {
print('Connected successfully');
Map map = d.value;
String val1 = map["val1"];
String val2 = map["val2"];
String val3 = map["val3"];
}

但是您应该首先对其进行测试,因为在那种情况下我没有测试过isNotEmpty函数,因此您应该对其进行测试,并查看行代码的用量

await database
      .reference()
.child("my/child/node")
    .once()

为您提供成功的连接,并根据需要设置为“ if”条件。 即:

  if (await http.get("google.com")
    .timeout(Duration(seconds: 5),onTimeout: () {
print('Spent 5 seconds and no connection');
})==200) {
print('Connected successfully');}

或者,您可以在致电数据库线路之前检查Internet连接。 您可以使用类似this的东西。

   import 'dart:io';

try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  DataSnapshot d = await database.reference().child("my/child/node").once();
  Map map = d.value;
  String val1 = map["val1"];
  String val2 = map["val2"];
  String val3 = map["val3"];    }
} on SocketException catch (_) {
print('not connected');
}