skip to Main Content

I’m trying to get DocumentSnapshot from collection

this my code

Stream<QuerySnapshot> streamState() => collectionRef.snapshots();
return StreamBuilder<QuerySnapshot>(
    stream: auth.streamState(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
      if (snapshot.hasData){
        DocumentSnapshot doc = snapshot.data!.docs.elementAt(0);

        print(doc.id);
      }

      return Container(
      color: Colors.white,
    );
  }
);

it work fine but as you see I use elementAt(0)
I want to get doc by its id

I try with docs.where but fail.

3

Answers


  1. The data that you are getting from auth.streamState() is I suppose about authentication? You should get it by id there probably

    Login or Signup to reply.
  2. If you know the ID of the document you want to listen to, you can do:

    Stream<QuerySnapshot> streamState() => collectionRef.doc("the document ID").snapshots();
    

    And then the StreamBuilder becomes:

    return StreamBuilder<DocumentSnapshot>(
      stream: auth.streamState(),
      builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> asyncSnapshot){
        if (asyncSnapshot.hasData){
          DocumentSnapshot doc = asyncSnapshot.data!;
          print(doc.id);
        }
    
        return Container(
          color: Colors.white,
        );
      }
    );
    
    Login or Signup to reply.
  3. it will return all documents

    return StreamBuilder<QuerySnapshot>(
    stream: auth.streamState(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapshot){
    if (snapshot.hasData){
     return GridView.builder(
    gridDelegate:
    const SliverGridDelegateWithFixedCrossAxisCount(
    mainAxisExtent: 200,
    childAspectRatio: 1 / 1,
    crossAxisSpacing: 1,
    mainAxisSpacing: 1,
    crossAxisCount: 2),
    itemCount: snapshot.data?.docs.length,
    itemBuilder: (BuildContext context, int index) {
    print("${snapshot.data?.docs[index]["feildNameYouWant"]}");
    return Text("${snapshot.data?.docs[index]["feildNameYouWant"]}");
    },
    );
    }else{
    print("snapshot DONT hasData ");
    return CustomWidgetYouWant();
    
    }
    );}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search