简体   繁体   中英

Get DocumentSnapshot by its id from Firebase collection

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.

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,
    );
  }
);

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

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();

}
);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM