首页 > 解决方案 > 如何修复flutter中firestore的事务错误?

问题描述

我正在实现聊天应用程序,并且必须使用事务来同步用户的消息。但是,有致命错误会突然终止应用程序。我该怎么处理?

我为此搜索了很多材料,但没有解决方案。Github 问题与此相关,我已经写过关于此的问题

Future<void> sendMessage(String content,String receiver,String chatRoomID) async {
  DocumentReference doc = Firestore.instance
    .collection(firestoreMessageCollection)
    .document(chatRoomID)
    .collection(chatRoomID)
    .document(DateTime.now().millisecondsSinceEpoch.toString());

  await Firestore.instance.runTransaction((tx) async{
    await tx.set(doc,{
      firestoreChatFromField: sl.get<CurrentUser>().uid,
      firestoreChatToField: receiver,
      firestoreChatTimestampField: DateTime.now().millisecondsSinceEpoch.toString(),
      firestoreChatContentField: content
    });
  });
}

我期望事务正常执行的正确结果,但发生以下错误并且应用程序被终止。

E/AndroidRuntime(1719):原因:java.lang.IllegalArgumentException:提供的文档引用来自不同的 Firestore 实例。

即使我使用相同的 Firestore 实例,它也会连续发生。有没有人解决了这个可怕的问题?

标签: darttransactionsfluttergoogle-cloud-firestore

解决方案


我也遇到了同样的问题。当我更新文档参考代码时,它已修复。您可以尝试更改文档参考吗

从:

DocumentReference doc = Firestore.instance
    .collection(firestoreMessageCollection)
    .document(chatRoomID)
    .collection(chatRoomID)
    .document(DateTime.now().millisecondsSinceEpoch.toString());

至:

DocumentReference doc = Firestore.instance.document('$firestoreMessageCollection/$chatRoomID/$chatRoomID/${DateTime.now().millisecondsSinceEpoch.toString()}');

我还更新了依赖版本。就我而言,这些是:

firebase_core: ^0.4.0+6
firebase_auth: 0.11.1+7
cloud_firestore: 0.12.5+2
firebase_storage: ^3.0.2
firebase_messaging: ^5.0.4
firebase_crashlytics: ^0.0.4+8

推荐阅读