Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

firebase - Flutter Firestore count documents real-time

I have a code in my flutter project which counts the number of documents in a collection where "accepted" is "pending".

QuerySnapshot notifNum = await orders.where("id",isEqualTo:_auth.currentUser.uid).where("accepted",isEqualTo: "pending").get();

Then I make a list of all the documents in the QuerySnapshot and get it's length, to get the number of notifications:

List<DocumentSnapshot> _notifc = notifNum.docs;
int notifCount = _notifc.length;

However, I want to make it real time so that, when a document is updated from "pending" to "accepted", the number of notifications is automatically updated. I tried using snapshots, but they didn't display any number. How can I make it work?

StreamBuilder<int>(
                        stream: _orders
                            .where("ustaId",isEqualTo:_auth.currentUser.uid)
                            .where("acceptedByUsta", isEqualTo: "pending")
                            .snapshots().length.asStream(),
                        builder: (context,snapshot) {
                          if(snapshot.hasError){
                            return Text("zzz");
                          }

                          if (snapshot.connectionState == ConnectionState.waiting) {
                            return Text("Loading");
                          }
                          if(snapshot.hasData){
                            print("aa");
                          }else{
                            print("zzz");
                          }
                          return new Positioned(
                                right: 0,
                                child: new Container(
                                  padding: EdgeInsets.all(1),
                                  decoration: new BoxDecoration(
                                    color: Colors.red,
                                    borderRadius: BorderRadius.circular(6),
                                  ),
                                  constraints: BoxConstraints(
                                    minWidth: 15,
                                    minHeight: 12,
                                  ),
                                  child: new Text(
                                    "aaa",
                                    style: new TextStyle(
                                      color: Colors.white,
                                      fontSize: 12,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ),
                              );
                        }),

enter image description here

question from:https://stackoverflow.com/questions/65842174/flutter-firestore-count-documents-real-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Follow these steps to implement the required functionality.

  1. You need to create a stream that returns the total number of documents where key 'accepted' has a value 'pending'.

  2. Encapsulate your widget that shows the count inside of a StreamBuilder or use StreamProvider somewhere above the `Scaffold' of the Widget displaying the count.

  3. Get data from the StreamBuilder and display on the widget.

Stream autoupdates whenever their is a change in the Firestore document.

I have changed my code to fit your need.

  1. Stream that returns count

      Stream<QuerySnapshot> requestCount() {
          return orders
          .where("ustaId",isEqualTo:_auth.currentUser.uid)
          .where("acceptedByUsta", isEqualTo: "pending")
          .snapshots();
    
          }
    
  2. Use a StreamBuilder

    StreamBuilder<QuerySnapshot>(
       stream: requestCount(),
       builder: (context, snapshot){
    
         if (snapshot.hasData){
    
           return Text(snapshot?.data.size.toString() ?? '0');
         }
         return Center(child: CircularProgressIndicator(),);
        }
       )
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...