Tushar Nikam
Tushar Nikam

Reputation: 1593

How to fetch auto generated document id in firebase firestore in flutter?

enter image description here

how can I get this random generated document's ID? Thank you for your help

Upvotes: 0

Views: 13727

Answers (3)

Peter Haddad
Peter Haddad

Reputation: 80904

You can get the documentId when adding the document:

  FirebaseFirestore.instance.collection("users").add(
  {
    "name" : "john",
    "age" : 50,
  }).then((value){
    print(value.id);
  });

Upvotes: 9

Aaditya Joshi
Aaditya Joshi

Reputation: 142

It's hard to give an accurate answer with seeing your code but here is an option:

StreamBuilder(
            stream: Firestore.instance
                .collection("cars")
                .snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Center(child: CircularProgressIndicator());
              } 
              else {
                  print(snapshot.data.documents[0].documentID) //this prints the document id of the (0th) first element in the collection of cars
               }
              })

You can use listview-builder to make a list and in the itemCount: property, you can use snapshot.data.documents.length and use index to access IDs of all elements in the following way: snapshot.data.documents[index].documentID

Upvotes: 0

Andrea
Andrea

Reputation: 329

If you're trying to read from Firestore, you get the entire collection by doing db.collection("users") and then you loop through the returned querySnapshot for each document returned. You can get the documentID that way. Here's the documentation for it.

db.collection("users").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        var id = doc.id; // randomly generated document ID
        var data = doc.data(); // key-value pairs from the document
    });
});

Upvotes: 4

Related Questions