How to Get Single Document From Firestore In Flutter?

· 3 min read
How to Get Single Document From Firestore In Flutter
How to Get Single Document From Firestore In Flutter

Earlier we have learned about How to Make a Count Query In Firebase so this time We will learn about How to Get a Single Document From Firestore in Flutter!

Are you Excited About Something New? Let’s dive into the same.

How to Get a Single Document From Firestore In Flutter?

To get a Single Document users cannot call the document() directly on your Firestore.instance. To solve this, you should use something like this:

var document = await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1');
document.get() => then(function(document) {
    print(document("name"));
})

Or in a simpler way:

var document = await Firestore.instance.document('COLLECTION_NAME/TESTID1');
document.get() => then(function(document) {
    print(document("name"));
});

While getting real-time data user need to make code snippet like the below:

Widget build(BuildContext context) {
  return new StreamBuilder(
      stream: Firestore.instance.collection('COLLECTION_NAME').doc('TESTID1').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return new Text("Loading");
        }
        var userDocument = snapshot.data;
        return new Text(userDocument["name"]);
      }
  );
}

If you want to use a Where Clause

await Firestore.instance.collection('collection_name').where(
    FieldPath.documentId,
    isEqualTo: "some_id"
).getDocuments().then((event) {
    if (event.documents.isNotEmpty) {
        Map<String, dynamic> documentData = event.documents.single.data; //if it is a single document
    }
}).catchError((e) => print("error fetching data: $e"));

Or Simply you can try DOCUMENT SNAPSHOT like a below:

DocumentSnapshot variable = await Firestore.instance.collection('COLLECTION NAME').document('DOCUMENT ID').get();

Conclusion:

Thanks for being with us on this flutter Journey!!! Stay connected 🙂

So in this article, We have been through How to Get Single Document From Firestore In Flutter.

Let us know what method did you try previously, in the comments right below!!

Thanks for Reading !!! Keep Fluttering !!! Drop us valuable feedback to serve you better.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

2 comments

Leave a Reply