【问题标题】:Flutter/Firebase realtime database - handle network errorsFlutter/Firebase 实时数据库 - 处理网络错误
【发布时间】:2021-02-06 06:55:33
【问题描述】:

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 不起作用,因为没有抛出异常,它只是等待。我想了解数据库连接错误。有可能吗?

【问题讨论】:

    标签: firebase flutter dart firebase-realtime-database network-connection


    【解决方案1】:

    你可以使用这样的超时:

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

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 1970-01-01
      • 2020-04-27
      • 2018-04-18
      • 2018-08-15
      • 1970-01-01
      • 2022-08-05
      • 2021-11-29
      • 1970-01-01
      相关资源
      最近更新 更多