首页 > 解决方案 > 如何使用 Flutter 在 FireStore 中创建集合中的文档

问题描述

集合在 Firebase 控制台上具有默认权限。

我使用电子邮件和密码正确登录了我的用户。

user = await _auth.signInWithEmailAndPassword( email: "email@gmail.com", password: "password");

然后在将图像成功上传到 FireStorage 后,我也尝试运行事务以更新文档。

  var fileName = _textController.text.toLowerCase();
  StorageUploadTask putFile =
      storage.ref().child("region/$fileName").putFile(_regionImage);

  UploadTaskSnapshot uploadSnapshot = await putFile.future;

  var regionData = new Map();
  regionData["label"] = _textController.text;
  var pictureData = new Map();
  pictureData["url"] = uploadSnapshot.downloadUrl.toString();

  pictureData["storage"] = "gs://app-db.appspot.com/region/$fileName";
  regionData["picture"] = pictureData;

  DocumentReference currentRegion =
      Firestore.instance.collection("region").document(fileName);

  Firestore.instance.runTransaction((transaction) async {
    DocumentSnapshot freshSnap = await transaction.get(currentRegion);
    print(freshSnap.exists);
    //await transaction.set(freshSnap.reference, regionData);
    await transaction.set(currentRegion, regionData);
    print("instance created");
  });

尝试运行事务时出现此错误。

如果我尝试设置为freshSnap.reference或直接设置为currentRegion. https://gist.github.com/matejthetree/f2a57c929d01919bd46da8ca6d5b6fb1

请注意,在第 15 行交易开始时出错,但在我没有收到 FireStorage 的身份验证令牌错误之前,尽管我成功地将图像上传和下载到存储。

我应该如何在 FireStore 中创建文档

标签: firebaseflutter

解决方案


似乎问题出在我创建地图的方式上。

  Map<String, dynamic> regionData = new Map<String, dynamic>();
  regionData["label"] = _textController.text;
  Map<String, dynamic> pictureData = new Map<String, dynamic>();
  pictureData["url"] = uploadSnapshot.downloadUrl.toString();

  pictureData["storage"] = "gs://app-db.appspot.com/region/$fileName";
  regionData["picture"] = pictureData;

  DocumentReference currentRegion =
      Firestore.instance.collection("region").document(fileName);

  Firestore.instance.runTransaction((transaction) async {
    await transaction.set(currentRegion, regionData);
    print("instance created");
  });

这段代码现在有效


推荐阅读