'Cloud Firestore: Write document reference from Flutter Plugin/SDK

I'm looking to write a document reference from a Flutter app to Firestore.

This is how it looks if I create a reference from the Firestore Console: enter image description here

If I just write the references inside a String from Flutter

  Map<String, String> usersReference = {
    uid: 'users/' + uid
  };
  Map<String, Object> userData = {
    'usersReference': usersReference
  };
  Firestore.instance.collection('chats').add(userData).then((doc) {
    doc.setData(userData);
  });

I get this:

enter image description here

Is there a way to write a reference (like from the Console) using the Flutter cloud_firestore plugin or any other SDK?



Solution 1:[1]

You should not declare an Object for the reference change it to DocumentReference

Map<String, DocumentReference> userData = {
  'usersReference': usersReference
};
Firestore.instance.collection('chats').add(userData).then((doc) {
  doc.setData(userData);
});

Solution 2:[2]

Yeah, you can add a document reference in a document but it is not preferred in the development environment. You may use this on the Firestore console only.

This episode from #AskFirebase might help you understand it properly.

Solution 3:[3]

First thing you will want to do is create the actual reference to the Document such as

DocumentReference userRef = FirebaseFirestore.instance.collection("users").doc(FirebaseAuth.instance.currentUser?.uid);

This references the "users" collection and then picks the document with the users uid.

Next, all you have to do is set your data.

var farmData = {
    'name': farmName,
    'address': farmAddress,
    'city': farmCity,
    'state': farmState,
    'zipcode': farmZip,
    'phone': farmPhone,
    'alternatePhone': farmAlternatePhone,
    'created': DateTime.now(),
    'users': [userRef]
  };

await FirebaseFirestore.instance.collection('farms').doc(uuid).set(farmData);

In my case I want a list of user references. Right now that table will only have 1 item in it, but I can update it with more users if I decide to later.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JLouage
Solution 2 Ahmad Khan
Solution 3 ttorbik