Flutter and Firestore: How can I get the document Id from the add function?

228

Solution 1

Do this

User user = FirebaseAuth.instance.currentUser;

FirebaseFirestore.instance.collection('room').add({
    'id': user.uid,
    'name': _name,
    'points': 0,
});

Solution 2

Add .then method at the end.

Do what ever you need with docRef.

FirebaseFirestore.instance.collection('room').add({
    'name': _name,
    'points': 0,
}).then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})

Solution 3

The add method on CollectionReference returns a Future<DocumentReference>. [Documentation]

Future<DocumentReference> add(Map<String, dynamic> data) async {
  final DocumentReference newDocument = doc();
  await newDocument.set(data);
  return newDocument;
}

So, try this:

FirebaseFirestore.instance.collection('room')
  .add({
    'name': _name,
    'points': 0,
  })
  .then((docRef) => print(docRef.id));
Share:
228
Sebastian
Author by

Sebastian

Updated on December 12, 2022

Comments

  • Sebastian
    Sebastian over 1 year

    I added a document to Firestore. How can I get the document Id of my added document? I want to save it to a variable.

    Btw. I'm using this for a web app if this Is important.

    FirebaseFirestore.instance.collection('room').add({
        'name': _name,
        'points': 0,
    });