【问题标题】:flutter firestore setData no error if no network connection is available如果没有可用的网络连接,flutter firestore setData 没有错误
【发布时间】:2019-05-15 10:44:30
【问题描述】:

代码如下:

createOrder(Order order) {
    loading.add(true);
    _auth.currentUser().asStream().asyncMap((FirebaseUser user) async {
      DocumentReference ref = firestore.collection('orders').document();

      order = order.copyWith(
          uid: user.uid,
          createdAt: FieldValue.serverTimestamp(),
          updatedAt: FieldValue.serverTimestamp());

      return await ref.setData(order.toJson()).catchError((e){
        print('OrderBloc catchError: ${e.toString()}');
        loading.add(false);
        errors.add(ErrorHandler.handle(e));
      });
    }).listen((data) {
      loading.add(false);
      createOrderSubject.add(null);
    }).onError((e) {
      print('OrderBloc: ${e.toString()}');
      loading.add(false);
      errors.add(ErrorHandler.handle(e));
    });
  }

问题是当设备上没有可用的互联网连接时,它既不会调用catchError 也不会调用onError

所以结果是加载微调器永远保持旋转。

我在日志中看到了这个错误: I/OkHttpClientTransport(16453): javax.net.ssl.SSLException: Write error: ssl=0x7f6856b188: I/O error during system call, Broken pipe

那么为什么 onError 和 catch 错误没有被执行呢?如何解决?

【问题讨论】:

  • _auth.currentUser() 仅在用户登录或登录失败时获取值。如果没有网络连接,则这两种情况都不成立。您通常希望在调用 _auth.currentUser() 之前检测到网络连接的缺失,或者在代码中设置超时以放弃尝试。
  • SSLException 怎么样,它没有被捕获,为什么?
  • 如果在建立安全连接时出现问题,这很可能发生在客户端。这通常会引发常规异常,而 onError 用于服务器上发生的错误。
  • 在这种情况下有没有办法捕获客户端异常?

标签: dart flutter google-cloud-firestore


【解决方案1】:

FlutterFire cloud_firestore 默认启用离线数据持久性,如docs 中所述。这应该会在设备重新连接网络时自动处理操作。

如果您需要检查设备当前是否连接到网络,您可以考虑使用connectivity_plus插件。

@override
initState() {
  super.initState();

  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // Handle network connectivity status
    // https://pub.dev/documentation/connectivity_plus_platform_interface/latest/connectivity_plus_platform_interface/ConnectivityResult.html
    if (result == ConnectivityResult.none) {
      // Not connected to network
    }
  });
}

// Be sure to cancel subscription once done
@override
dispose() {
  super.dispose();
  subscription.cancel();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2021-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多