How do I get documentid of a firestore document in flutter?

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


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

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.