问题描述
我已经对此进行了大量搜索。但是,我的 Flutter 应用程序在活动网络上运行良好。我已为 cloud_firestore 启用持久性,但显示此错误:
[cloud_firestore/unavailable] The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff.
我的示例代码:
FirebaseFirestore db = FirebaseFirestore.instance;
db.settings = Settings(persistenceEnabled: true,cacheSizeBytes: 10000000);
final ref = db.doc("some_collection/some_doc");
try{
ref.update({"key": value});
} catch(error) {
print(error.toString());
}
我的pubspec.yaml
:
firebase_messaging: ^8.0.0-dev.14
firebase_core: ^0.7.0
firebase_auth: ^0.20.0+1
Flutter_local_notifications: ^3.0.3
cloud_firestore: ^0.16.0
解决方法
因此,我的情况是,每当我的应用程序收到来自客户端的传入消息时,我都必须将一些数据上传到 firestore。这就是为什么我需要两个服务,一个是后台消息接收器和 Firestore 持久化。
我在做什么:
尝试首先从 firestore 读取一些数据,然后我需要将传入的消息数据再次放入 firestore。像这样:
FirebaseFirestore db = FirebaseFirestore.instance;
db.settings = Settings(persistenceEnabled: true,cacheSizeBytes: 10000000);
// payments ref
final paymentRefs = db
.collection("payments")
.where("trxID",isEqualTo: "123456")
.where("amount",isEqualTo: 50)
.limit(1);
try {
final paymentGet = await paymentRefs.get();
if (paymentGet.size > 0) {
final paymentData = paymentGet.docs[0];
// check for payment existence with the trxID
// if exists,then validate and update
if (paymentData.exists) {
final paymentAmount = paymentData.data()['amount'];
final exactPaymentRef = db.collection("payments").doc(paymentData.id);
// for individual and if amount matches
if (amount == paymentAmount) {
exactPaymentRef.update({
"paid": true
});
}
} else {
// payment ref not found with trxID
// so upload the trxID to reqTrxID collection
db.doc("reqTrxID/$trxID").set({
"createdAt": new DateTime.now().millisecondsSinceEpoch,"phoneNumber": phoneNumber,"amount": amount
});
}
}
} catch (error) {
print("error triggering to firestore: ${error.toString()}");
}
我的错误是,我正在从 firestore 中进行一些额外的提取。并且作为 firebase 文档firestore 持久性不适用于任何异步(try/catch、promise、async/await)方式(我很高兴这样做:))。
我是如何解决这个问题的:
FirebaseFirestore db = FirebaseFirestore.instance;
db.doc("reqTrxID/$trxID").set({
"createdAt": new DateTime.now().millisecondsSinceEpoch,"amount": amount
});
我只是上传我必须上传的值,并进行所有必要的检查,然后将它们发送到文档创建触发器上的云功能。这解决了我的问题。