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

Flutter/Firebase realtime database - handle network errors

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"];

有效。但是,当没有网络连接时,它会无休止地等待。我想捕获错误(无法连接到数据库)。我该怎么做? Try/catch 不起作用,因为没有抛出异常,它只是等待。我想被告知数据库连接错误。可能吗?

你可以像这样使用超时:

 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');}

或者您可以在调用数据库线路之前检查互联网连接。 你可以使用 .

之类的东西
   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');
}