dart - 在 Dart 的 Cloud Firestore 中添加文档后如何获取文档 ID

我正在使用以下代码使用 Dart/Flutter 更新 Cloud Firestore 集合。

  final docRef = Firestore.instance.collection('gameLevels');
  docRef.document().setData(map).then((doc) {
    print('hop');
  }).catchError((error) {
    print(error);
  });

我试图获取在将文档添加到集合时创建的 documentID,但 (doc) 参数返回为 null。我以为它应该是一个文档引用?

既然是null,我显然不能使用doc.documentID。

我做错了什么?

最佳答案

您可以尝试以下方法:

DocumentReference docRef = await 
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);

由于 add() 方法创建新文档并自动生成 id,因此您不必显式调用 document() 方法

或者,如果您想使用“then”回调,请尝试以下操作:

  final collRef = Firestore.instance.collection('gameLevels');
  DocumentReferance docReference = collRef.document();

  docReferance.setData(map).then((doc) {
    print('hop ${docReferance.documentID}');
  }).catchError((error) {
    print(error);
  });

https://stackoverflow.com/questions/51054460/

相关文章:

ios - flutter : Not Connecting to IOS Simulator in

javascript - Flutter 是否使用 Javascript 引擎之类的东西,例如 Re

dart - flutter 列不展开

dart - 如何为屏幕设置不同的主题?

flutter - 构造函数中的 Key 参数是什么

java - Flutter 无法从 url 加载图片

dart - 在 Flutter 中保持响应的同时制作持久的背景图像

dart - Flutter:如何获取 http 请求的上传/下载进度

android-studio - Flutter 如何在 Android Studio 中制作发布版

c# - 将 Flutter 前端与 Android 和 iOS 的 .NET Core 后端相结合