Search code examples
flutterfirebasedartgoogle-cloud-firestoreflutter-streambuilder

How to StreamBuild a single document in flutter


I have this code

  Stream<List<Ticket>> readTicket() => FirebaseFirestore.instance
      .collection('tickets')
      .where("added_by", isEqualTo: member?.uid)
      .snapshots()
      .map(
        (snapshots) => snapshots.docs
            .map(
              (doc) => Ticket.fromJson(
                doc.data(),
              ),
            )
            .toList(),
      );

It does exactly want I wanted to do but I want the one that will return a single document from database instead of list of documents.

Here is the UI

StreamBuilder<List<Ticket>>(
        stream: TicketController().readTicket(),
        builder: (context, snapshot) {
//.......
}
);

I want this code to fetch only the first document and not the list of documents.


Solution

  • Try

     Stream<Ticket> readTicket() => FirebaseFirestore.instance
          .collection('tickets')
          .doc("kkkk")
          .snapshots()
          .map((DocumentSnapshot<Map<String, dynamic>> snapshot) =>
              Ticket.fromJson(snapshot.data()!));
    

    Then in your UI

    StreamBuilder<Ticket>(
            stream: TicketController().readTicket(),
            builder: (context, snapshot) {
    //.......
    }
    );