25

I have tried the following but it returns a random string which is not present in the firestore.

I did manage to get documentid of parent collection using a Query Snapshot

DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

                    var doc_id2=doc_ref.documentID;

More Code: I am getting an error in trying to access the document id. I have tried to use await but its giving an error.

 Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(
            title: new Text(
              "National Security Agency",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.normal,
                  fontSize: 24.0),
            ),
            backgroundColor: Colors.redAccent,
            centerTitle: true,
            actions: <Widget>[
              new DropdownButton<String>(
                items: <String>['Sign Out'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) => logout(),
              )
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
    
            },
            child: Icon(Icons.search),
          ),
    
          body: StreamBuilder (
              stream: cloudfirestoredb,
    
    
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
    
                    return new ListView(
                      children: snapshot.data.documents.map((document) {
    
    
                        var doc_id=document.documentID;
                        var now= new DateTime.now();
                        var formatter=new DateFormat('MM/dd/yyyy');
                        String formatdate = formatter.format(now);
                        var date_to_be_added=[formatdate];
    
                        DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
    
                       var doc_id5= await get_data(doc_ref);
    
    
                        print(doc_id);
                        
    
    
                        Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
                        return cardtemplate(document['Name'], document['Nationality'], doc_id);
    
                        }).toList(),
                    );
                  },
           ),
              );
      }
peterh
  • 11,875
  • 18
  • 85
  • 108
Pruthvik Reddy
  • 275
  • 1
  • 3
  • 10

9 Answers9

24

You have to retrieve that document for its id.

Try this

DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

DocumentSnapshot docSnap = await doc_ref.get();
var doc_id2 = docSnap.reference.documentID;

Make sure you use this in a function marked as async since the code uses await.

Edit : To answer your question in the comments

Future<String> get_data(DocumentReference doc_ref) async { 
  DocumentSnapshot docSnap = await doc_ref.get(); 
  var doc_id2 = docSnap.reference.documentID; 
  return doc_id2; 
}

//To retrieve the string
String documentID = await get_data();

Edit 2 :

Just add async to the map function.

snapshot.data.documents.map((document) async {
  var doc_id=document.documentID;
  var now= new DateTime.now();
  var formatter=new DateFormat('MM/dd/yyyy');
  String formatdate = formatter.format(now);
  var date_to_be_added=[formatdate];

  DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

  var doc_id5= await get_data(doc_ref);

  print(doc_id);

  Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
  return cardtemplate(document['Name'], document['Nationality'], doc_id);
}).toList(),

let me know if this works

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Abdul Malik
  • 1,158
  • 6
  • 15
  • I have added the following function. But how can I get the string from Future String Instance Future get_data(DocumentReference doc_ref) async{ DocumentSnapshot docSnap = await doc_ref.get(); var doc_id2 = docSnap.reference.documentID; return doc_id2; } – Pruthvik Reddy Jul 18 '20 at 13:18
  • Thank you. But I am getting an error using await. May be because I am not using Future Builder. I am using Stream Builder and its returning a list view. How do i solve this? – Pruthvik Reddy Jul 18 '20 at 13:53
  • Check this once – Abdul Malik Jul 18 '20 at 16:50
  • Thank you for your time. I tried another way by using another function and initialising it at the start. It worked. Thanks for helping me out – Pruthvik Reddy Jul 18 '20 at 20:29
  • Your welcome, anytime! if you really think this answer helped you, could you mark it as answered? (green tick). Stack overflow rewards reputation based on that, which helps me answer others. Thanks ! – Abdul Malik Jul 19 '20 at 05:06
  • I guess, this approach no longer works, atleast for me(I mean that, documentID!) – An Android May 14 '21 at 04:54
  • Pls help me with this:-https://stackoverflow.com/questions/67941537/how-to-get-a-doc-id-which-is-random-or-unknown-in-flutter-from-firebasefirestore – GAGAN SINGH Jun 12 '21 at 05:01
11

After the updates, you can now use this line of code to access the doc id,

snapshot.data.docs[index].reference.id

where snapshot is a QuerySnapshot.

Here is an example.

FutureBuilder(
    future: FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('addresses')
        .get(),
    builder: (context, AsyncSnapshot snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(child: CircularProgressIndicator());
      }else{return Text(snapshot.data.docs[0].reference.id.toString());}
koushik datta
  • 181
  • 2
  • 3
8

You can fetch documentId using value.id after the adding values in documents in this way:-

CollectionReference users = FirebaseFirestore.instance.collection('candidates');
  
  Future<void> registerUser() {
 // Call the user's CollectionReference to add a new user
     return users.add({
      'name': enteredTextName, // John Doe
      'email': enteredTextEmail, // Stokes and Sons
      'profile': dropdownValue ,//
      'date': selectedDate.toLocal().toString() ,//// 42
    })
        .then((value) =>(showDialogNew(value.id)))
        .catchError((error) => print("Failed to add user: $error"));
  }

Here, value.id gives the ducumentId.

Rahul Kushwaha
  • 5,473
  • 3
  • 26
  • 30
8
  • To get the document ID in a collection:

    var collection = FirebaseFirestore.instance.collection('collection');
    var querySnapshots = await collection.get();
    for (var snapshot in querySnapshots.docs) {
      var documentID = snapshot.id; // <-- Document ID
    }
    
  • To get the document ID of a newly added data:

    var collection = FirebaseFirestore.instance.collection('collection');
    var docRef = await collection.add(someData);
    var documentId = docRef.id; // <-- Document ID
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
4

document() when you calling this method without any path, it will create a random id for you.

From the docs:

If no [path] is provided, an auto-generated ID is used. The unique key generated is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.

Therefore if you want to get the documentID, then do the following:

var doc_ref = await Firestore.instance.collection("board").document(doc_id).collection("Dates").getDocuments();
doc_ref.documents.forEach((result) {
  print(result.documentID);
});
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Thank you. I have tried to implement it in an async function but receiving an error while trying to return it. I tried to use "await"...but not helping. Kindly review my code added in the question – Pruthvik Reddy Jul 18 '20 at 14:45
  • this workd for me but can i list them in listview builder – Tripping Oct 27 '20 at 06:25
3

You can also do the following

Firestore.instance
    .collection('driverListedRides')
    .where("status", isEqualTo: "active")
    .getDocuments()
    .then(
      (QuerySnapshot snapshot) => {
        driverPolylineCordinates.clear(),
        snapshot.documents.forEach((f) {
        
          print("documentID---- " + f.reference.documentID);
         
        }),
      },
    );
gsm
  • 2,348
  • 17
  • 16
2

Hi there comign from 2022 with cloud_firestore: ^3.1.0 you can get the uid by doing the followign:

First of all I ask you to note that we aren't store a new field for the id, it would be kind of repetition. So we do instead want to get the auto generated uid, which stand for unique id.

Model layer.

class Product {
  late final String _id;
  String get id => _id;
  set id(String value) {
    _id = value;
  }

  final String title;
  final String description;

  Product({
    required this.title,
    required this.description,
  });

  factory Product.fromJson(Map<String, dynamic> jsonObject) {
    return Product(
      title: jsonObject['title'] as String,
      description: jsonObject['description'] as String,
    );
  }
}

A very common model, the only special thing is the id property.

Data layer. Here where the data will be fetched.

class ProductData {
  //create an instance of Firestore.
  final _firestore = FirebaseFirestore.instance;
  
  // A simple Future which will return the fetched Product in form of Object.
  Future<List<Product>> getProducts() async {
    final querySnapshot = await _firestore.collection('products').get();
    final products = querySnapshot.docs.map((e) {
      // Now here is where the magic happens.
      // We transform the data in to Product object.
      final model = Product.fromJson(e.data());
      // Setting the id value of the product object.
      model.id = e.id;
      return model;
    }).toList();
    return products;
  }
}

That was all, hopefully I was clear Good coding!

Just to be sure you got the idea, we get the underlined id. enter image description here

Talat El Beick
  • 423
  • 6
  • 12
0
  QuerySnapshot docRef = await  FirebaseFirestore.instance.collection("wedding cards").get();

print(docRef.docs[index].id);

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 03 '23 at 23:54
0

This is one of the way we can do it.

QuerySnapshot snap = await FirebaseFirestore.instance
    .collection("TechnovationHomeScreen")
    .doc('List')
    .collection('Demo')
    .get();
snap.docs.forEach((document) {
  print(document.id);