Home > Enterprise >  How to StreamBuild a single document in flutter
How to StreamBuild a single document in flutter

Time:10-01

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.

CodePudding user response:

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) {
//.......
}
);

CodePudding user response:

To fetch one doucment try this code snippet;

suppose this is your ticket Model class:

import 'package:cloud_firestore/cloud_firestore.dart';


  class TicketModel{
  final String? ticketId;
  final String? added_by;
  final Timestamp? createAt;

  TicketModel({
    this.ticketId,
    this.added_by,
    this.createAt,
  });

  factory TicketModel.fromSnapshot(DocumentSnapshot snapshot) {
    return TicketModel(
      ticketId: snapshot.get('ticketId'),
      added_by: snapshot.get('added_by'),
      createAt: snapshot.get('createAt'),
    );
  }

  Map<String, dynamic> toDocument() {
    return {
      "ticketId": ticketId,
      "added_by": added_by,
      "createAt": createAt,
    };
  }
}
  1. Create Stream method like below:

     Stream<List<TicketModel>> readTicket(String uid) {
    return FirebaseFirestore.instance
        .collection("tickets")
        .where("added_by", isEqualTo: uid)
        .limit(1).snapshots().map(
        (querySnapshot) => 
            querySnapshot.docs.map((e) => 
                TicketModel.fromSnapshot(e)).toList());
    

    }

  2. Now call readTicket method check code snippet

     StreamBuilder<List<TicketModel>>(  
         stream: readTicket("user_id"),  
        builder: (context, snapshot) {  
          if (snapshot.hasData == false) { 
             return centerProgressBarIndicator();  
          } 
           if (snapshot.data!.isEmpty) {  
            return Container();  
           }  
             final ticketData = snapshot.data!.first; 
          return Column(  
             children: [
                 Text("TicketId: ${ticketData.ticketId}"),  
                 Text("added_by: ${ticketData.added_by}"),  
               ], 
             ); 
           },
         )
    
  • Related