你可以使用这样的超时:
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');}
或者您可以在调用数据库线路之前检查互联网连接。
你可以使用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');
}