Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create document in collection in FireStore with Flutter

Collection has default permissions on Firebase Console.

I sign in my user correctly with email and password.

user = await _auth.signInWithEmailAndPassword( email: "[email protected]", password: "password");

Then after uploading image successfully to FireStorage, I try to run a transaction as well to update the document.

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

I get this error when trying to run a transaction.

It is the same If I try to set to freshSnap.reference or directly to currentRegion. https://gist.github.com/matejthetree/f2a57c929d01919bd46da8ca6d5b6fb1

Note that at line 15 error for transaction starts, but before I get no auth token error as well for FireStorage although I successfully upload and download images to storage.

How should I approach document creation in FireStore

like image 477
Tree Avatar asked Jan 02 '23 09:01

Tree


1 Answers

Seems like the problem was in the way I created the map.

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

this code works now

like image 88
Tree Avatar answered Apr 19 '23 06:04

Tree