Pruthvik Reddy
Pruthvik Reddy

Reputation: 285

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

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

Upvotes: 26

Views: 73501

Answers (9)

Talat El Beick
Talat El Beick

Reputation: 541

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

2024 Update

Instead of declaring late variable, you could pass the ID via the factory constructed.

class Product {
  final String id;
  final String title;
  final String description;

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

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

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) => 
       Product.fromJson(e.id, e.data())).toList();

   return products;
  }
}

As you may expect this much better approach since there is no reassignable variables they are all finals.

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

Upvotes: 2

Sakshi Kulkarni
Sakshi Kulkarni

Reputation: 1

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

Upvotes: 0

jenil SpSoftTech
jenil SpSoftTech

Reputation: 11

  QuerySnapshot docRef = await  FirebaseFirestore.instance.collection("wedding cards").get();

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

Upvotes: 0

Abdul Malik
Abdul Malik

Reputation: 1188

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

Upvotes: 26

koushik datta
koushik datta

Reputation: 339

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

Upvotes: 12

CopsOnRoad
CopsOnRoad

Reputation: 268374

  • 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
    

Upvotes: 9

Rahul Kushwaha
Rahul Kushwaha

Reputation: 6752

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.

Upvotes: 8

gsm
gsm

Reputation: 2426

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

Upvotes: 3

Peter Haddad
Peter Haddad

Reputation: 80944

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

Upvotes: 4

Related Questions