Devi Suresh
Devi Suresh

Reputation: 139

FLUTTER, FIRESTORE : I have a streambuilder that returns a certain field from all the documents in the collection..how do I add query?

I have a collection called todo and each document in todo contains the fields : task, boolean isDone, user_id, and task_id. Each user in my app has an ID so I only want to retrieve the tasks for their id. I have the code to retrieve the task field from all the documents but I want to query the collection so that I only retrieve the tasks for where the user_id=docid..docid is the variable i know.

body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection('todo').snapshots(),
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot course = snapshot.data.docs[index];
                  return ListTile(title: Text(course['task']));
                });
          },
        )

So I need help adding a query to this. I don't think i can use index anymore, though i am unsure . I am new to Flutter and Firestore so all the Streambuiler and Futurebuilder things haven't clicked yet. Please lmk if there any easy to understand references out there also.

Upvotes: 0

Views: 3341

Answers (2)

Jigar Patel
Jigar Patel

Reputation: 5423

You can add a query like so.

stream: FirebaseFirestore.instance
            .collection('todo')
            .where('user_id', isEqualTo: docid)
            .snapshots(),

Upvotes: 1

Tarik Huber
Tarik Huber

Reputation: 7408

You can use any query as explained in the documentation by just adding it to your StreamBuilder like this:

body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection('todo').orderBy('timestamp')
  .limitToLast(2).snapshots(),
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot course = snapshot.data.docs[index];
                  return ListTile(title: Text(course['task']));
                });
          },
        )

You can also use the where and all other queries. The StreamBuilder basically is just a syntax helper to help you awoid working with state when you use a realtime stream. If you would not have it you would need to initialize the stream in the init override of your Widget and change the state of a local variable each time the stream changes. With the StreamBuilder you just avoid that and get a much cleaner code. You also don't need to convert your stateless widget to a statefull one if you don't want to.

The firestore query you use in the stream param is absolutely the same as in the decumentation so you can follow it regardless if you use it on it's own or in a StreamBuilder.

Upvotes: 2

Related Questions