Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(),
                    );
                  },
           ),
              );
      }
like image 904
Pruthvik Reddy Avatar asked Jul 18 '20 12:07

Pruthvik Reddy


People also ask

How do I get data from a firestore document?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.


7 Answers

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());}
like image 194
koushik datta Avatar answered Oct 21 '22 01:10

koushik datta


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

like image 38
Abdul Malik Avatar answered Oct 21 '22 03:10

Abdul Malik


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.

like image 40
Rahul Kushwaha Avatar answered Oct 21 '22 02:10

Rahul Kushwaha


  • 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
    
like image 40
CopsOnRoad Avatar answered Oct 21 '22 01:10

CopsOnRoad


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);
});
like image 43
Peter Haddad Avatar answered Oct 21 '22 02:10

Peter Haddad


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);
         
        }),
      },
    );
like image 37
gsm Avatar answered Oct 21 '22 03:10

gsm


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

like image 27
Talat El Beick Avatar answered Oct 21 '22 03:10

Talat El Beick