Home > OS >  How to retrive all the documents of firestore at once using flutter?
How to retrive all the documents of firestore at once using flutter?

Time:11-30

I am building an Appointment Booking application want to retrieve all my documents from firestore at once on a button click. I used this:

Future<void> userAppointmentHistory() async {
    String collectionName =
        FirebaseAuth.instance.currentUser?.displayName as String;
    String doc_id = "YyWqd9VlB1IdmYoIIFTq";
    await FirebaseFirestore.instance
        .collection(collectionName)
        .doc(doc_id)
        .snapshots()
        .listen(
      (event) {
        print(
          event.get("selectedDate"),
        );
      },
    );
  }

From the above code, I am getting only the specified document id details. So please help me modify the above code so that I get all the document details as I want to display these details on cards as my booked appointment history.

CodePudding user response:

Here you are passing the doc id String doc_id = "YyWqd9VlB1IdmYoIIFTq"; You don't want to pass that if you want the full documents. just pass the collection reference.

Follow the below code

 fetchData() {
    CollectionReference collectionReference =
        FirebaseFirestore.instance.collection(collectionName);
    collectionReference.snapshots().listen((snapshot) {
      setState(() {
        document = snapshot.docs;
      });
      print(document.toString);
    });
  }

CodePudding user response:

Rudransh Singh Mahra,

It's as easy as putting text widget in our application.

Solution

You did it in right way but by mistake you have passed a specific id of documents in doc() as doc('YyWqd9VlB1IdmYoIIFTq'). you just need to remove that id from there and you may get your desired output.

What actually happens :

In your query you pass specific docId. So that it will returns that specified id document from your collection. To get all the documents from that collection you just need to do as follows,

Future<void> userAppointmentHistory() async {
    String collectionName =
        FirebaseAuth.instance.currentUser?.displayName as String;
    // String doc_id = "YyWqd9VlB1IdmYoIIFTq";
    await FirebaseFirestore.instance
        .collection(collectionName)
        .doc()
        .snapshots()
        .listen(
      (event) {
        print(
          event.get("selectedDate"),
        );
      },
    );
  }

And you will get your desired output if collectionName is valid and exist in firestorm database.

  • Related