首页 > 解决方案 > Firebase get call 适用于 android,但在 iOS 上有一个奇怪的行为

问题描述

我有一个颤振应用程序,我的客户已经在 android 上使用了将近 2 个月,现在我也必须制作 iOS 版本。

当我尝试使用 userAccount.id 运行 get 调用时,我得到了从 firebase 返回的数据 6 次,但随后出现“事务重试失败”错误。

我尝试了所有可以在谷歌上找到的东西。

注意:来自 firebase 的流式数据可以正常工作

我正在使用 cloud_firestore 颤振包

这是功能:

  static Future<WebRequestResponse> getUserAccountByID(String id) async {
    if (!await isInternetConnectionAvailable()) {
      return WebRequestResponse(false, null, null,
          errorType: ErrorType.ERROR_NO_INTERNET_CONNECTION);
    }
    DocumentSnapshot ds;
    final TransactionHandler getTransaction = (Transaction tx) async {
      ds = await tx.get(userAccountsCollection.document(id));
      print(ds.data);
      return ds.data;
    };

    WebRequestResponse response = WebRequestResponse(false, null, null);
    return Firestore.instance.runTransaction(getTransaction).then((jsonData) {
      print(jsonData);
      UserAccount userAccount = UserAccount.fromJson(jsonData);
      print(userAccount.id);
      if (userAccount.id != null) {
        response.success = true;
        response.data = userAccount;
        return response;
      } else {
        response.success = false;
        response.errorType = ErrorType.ERROR_USER_NOT_FOUND;
        return response;
      }
    }).catchError((error) {
      print('get_user_account_by_id_error: $error');
      response.success = false;
      response.error = error;
      response.errorType = ErrorType.ERROR_UNKNOWN;
      return response;
    });
  }

这是我得到的回应:

flutter: {id: Edaavf39l4Y3cbfGy4RblYSdy1p1, profilePictureURL: https://firebasestorage.googleapis.com/v0/b/fr<REDACTED REST OF JSON>}
flutter: {id: Edaavf39l4Y3cbfGy4RblYSdy1p1, profilePictureURL: https://firebasestorage.googleapis.com/v0/b/fr<REDACTED REST OF JSON>}
flutter: {id: Edaavf39l4Y3cbfGy4RblYSdy1p1, profilePictureURL: https://firebasestorage.googleapis.com/v0/b/fr<REDACTED REST OF JSON>}
flutter: {id: Edaavf39l4Y3cbfGy4RblYSdy1p1, profilePictureURL: https://firebasestorage.googleapis.com/v0/b/fr<REDACTED REST OF JSON>}
flutter: {id: Edaavf39l4Y3cbfGy4RblYSdy1p1, profilePictureURL: https://firebasestorage.googleapis.com/v0/b/fr<REDACTED REST OF JSON>}
flutter: get_user_account_by_id_error: PlatformException(9, Transaction failed all retries., null)

如您所见,事务内的 print 正确打印了数据,但它发生了 6 次,之后又失败了。知道为什么会发生这种情况以及如何解决吗?

非常感谢

标签: iosfirebasedartflutter

解决方案


所以经过几周的挣扎和随机尝试后,我认为这可能是因为我在虚拟机中运行颤振(尚无法确认)。

无论如何,对我来说,解决方案是在每次 tx.get 调用之后,我必须添加一个具有相同文档 ID 的 tx.set 调用并使用空数据进行更新。我不知道为什么,或者这是如何工作的,但确实如此。我虽然会回答,以防将来有人遇到同样的问题。


推荐阅读