Home > Mobile >  Retrieve data from a specific document only within a collection - Firestore
Retrieve data from a specific document only within a collection - Firestore

Time:06-01

I have a collection, within it I have a number of documents. I want to retrieve only the time slots for each document individually and not those in the other collections. Is there a way that I can do this?

Excerpt of the code

Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        for (var i = 0; i < doc["time"].length; i  )
          Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 10.0,
              vertical: 10.0,
            ),
            child: availableSlot(doc["time"][i]),
          ),
      ],
    )

Firestore reference

final CollectionReference categoriesDetails =
      FirebaseFirestore.instance.collection("collection-name");

What I am currently reading as shown in the image below is data from all the other documents. I only want to retrieve data from one document based on user's route (Only the row of data should be seen. The others are from other documents and should not be seen)

enter image description here

This is my db

enter image description here

CodePudding user response:

you can use doc() and get() methods to get data from a specific document from a collection, here's how:

/// GetUserTime('barber');
class GetUserTime extends StatelessWidget {
  final String documentId;

  GetUserTime(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('categories');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
          return Column( 
            children : data['time'].map((time) => Text(time)).toList());
        }

        return Text("loading");
      },
    );
  }
}

CodePudding user response:

If you only want to read a single document:

final CollectionReference categoriesDetails =
  FirebaseFirestore.instance.collection("collection-name");
final DocumentReference categoryDetails = categoriesDetails.document("barber");

You can then use the categoryDetails in the StreamBuilder in your UI, and will get a single DocumentSnapshot rather than a QuerySnapshot with multiple documents.

  • Related