如何使用Flutter在FireStore中创建集合中的文档

时间:2018-05-19 01:47:54

标签: firebase flutter

Collection具有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行出现事务错误,但在我没有获得auth令牌错误之前,FireStorage也是如此,尽管我已成功上传图片并将其下载到存储空间。

我应该如何处理FireStore中的文档创建

2 个答案:

答案 0 :(得分:1)

似乎问题就在于我创建地图的方式。

  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");
  });

此代码现在可以使用

答案 1 :(得分:0)

Firestore 替换为 FirebaseFirestore 并且更新了很多 API。

var myData = {'foo': 0, 'bar': true};

var collection = FirebaseFirestore.instance.collection('collection');
collection 
    .add(myData) // <-- Your data
    .then((_) => print('Added'))
    .catchError((error) => print('Add failed: $error'));