60

Edit: This Question is outdated, and I am sure, new documentation and more recent answers are available as of now.

I want to retrieve data of only a single document via its ID. My approach with example data of:

TESTID1 {
     'name': 'example', 
     'data': 'sample data',
}

was something like this:

Firestore.instance.document('TESTID1').get() => then(function(document) {
    print(document('name'));
}

but that does not seem to be correct syntax.

I was not able to find any detailed documentation on querying firestore within flutter (dart) since the firebase documentation only addresses Native WEB, iOS, Android etc. but not Flutter. The documentation of cloud_firestore is also way too short. There is only one example that shows how to query multiple documents into a stream which is not what i want to do.

Related issue on missing documentation: https://github.com/flutter/flutter/issues/14324

It can't be that hard to get data from a single document.

UPDATE:

Firestore.instance.collection('COLLECTION').document('ID')
.get().then((DocumentSnapshot) =>
      print(DocumentSnapshot.data['key'].toString());
);

is not executed.

blandaadrian
  • 742
  • 1
  • 5
  • 16

11 Answers11

88

but that does not seem to be correct syntax.

It is not the correct syntax because you are missing a collection() call. You cannot call 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 more simpler way:

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

If you want to get data in realtime, please use the following code:

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

It will help you set also the name to a text view.

Harsh J
  • 413
  • 1
  • 4
  • 15
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 2
    The error you pointed out is true but is not the main problem. According to AndroidStudio: `the getter for DocumentReference is not defined`. So `document().get()` is invalid as well. I find there is a lack of information on the basic syntax of these queries. I have even read the [specification](https://pub.dartlang.org/documentation/firebase_firestore) – blandaadrian Nov 28 '18 at 12:26
  • 7
    You should also use `await`. Please see my updated answer. Does it work now? – Alex Mamo Nov 28 '18 at 12:38
  • I did vote +1, but it will only appear publicly when i earn enough reputation.. **Is there any documentation or resource on this, you can recommend?** – blandaadrian Nov 28 '18 at 13:31
  • 1
    Regarding Firebase, official docs. Regarding Firebase and Flutter I don't know. – Alex Mamo Nov 28 '18 at 13:33
  • 1
    I tried the realtime stream and I get this error `The argument type 'Stream' can't be assigned to the parameter type 'Stream'.`. Any idea ? – Théo Champion Feb 06 '19 at 02:07
  • @ThéoChampion Please post another question for that problem with its own [MCVE](https://stackoverflow.com/help/mcve) so me and other Firebase developers can help you. – Alex Mamo Feb 06 '19 at 08:46
  • there are some typos in the code arent they? document('name') should be document['name'] as far as i understand how documents work with firestore – Logemann Oct 01 '19 at 18:52
  • if I try to pass `userDocument` to a new page as an argument I cannot do `userDocument["name"]` on the second page. I get an error because `name` doesn't exist (but it's `Instance of 'DocumentSnapshot'`) – Dani Nov 28 '19 at 11:22
  • @Dani Without seeing your code, I cannot be much of a help. So please post another fresh question, so I and other Firebase developers can help you. – Alex Mamo Nov 28 '19 at 11:33
  • It's exactly the same as the code above van sending the params instead: `var userDocument = snapshot.data; Navigator.of(context).pushNamed( '/my-set', arguments: userDocument );` – Dani Nov 28 '19 at 11:46
  • 3
    got it. Passing now `userDocument.dat`, which is the actual map (https://stackoverflow.com/questions/56721694/convert-firestore-documentsnapshot-to-map-in-flutter) – Dani Nov 28 '19 at 12:16
  • Thank you @AlexMamo , you answer is helpful .. Thanks a lot – Sana'a Al-ahdal Feb 04 '20 at 11:13
  • @AlexMamo for me I am getting this question issue with Builder. can you look into my gist. I have attached code output. and printed document. https://gist.github.com/surapuramakhil/5dbbc060c92557c18ecab6e2dc9b9cbd – Akhil Surapuram May 24 '20 at 22:35
  • @AkhilSurapuram You should post a new question using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo May 25 '20 at 08:56
  • I believe "Firestore.instance..." has been deprecated in favor of "FirebaseFirestore.instance..." per documentation at https://firebase.flutter.dev/docs/migration/#firestore – Mark Gavagan Mar 03 '21 at 20:02
39

Null safe code (Recommended)

You can either query the document in a function (for example on press of a button) or inside a widget (like a FutureBuilder).

  • In a method: (one time listen)

    var collection = FirebaseFirestore.instance.collection('users');
    var docSnapshot = await collection.doc('doc_id').get();
    if (docSnapshot.exists) {
      Map<String, dynamic>? data = docSnapshot.data();
      var value = data?['some_field']; // <-- The value you want to retrieve. 
      // Call setState if needed.
    }
    
  • In a FutureBuilder (one time listen)

    FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
      future: collection.doc('doc_id').get(),
      builder: (_, snapshot) {
        if (snapshot.hasError) return Text ('Error = ${snapshot.error}');
    
        if (snapshot.hasData) {
          var data = snapshot.data!.data();
          var value = data!['some_field']; // <-- Your value
          return Text('Value = $value');
        }
    
        return Center(child: CircularProgressIndicator());
      },
    )
    
  • In a StreamBuilder: (always listening)

    StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
      stream: collection.doc('doc_id').snapshots(),
      builder: (_, snapshot) {
        if (snapshot.hasError) return Text('Error = ${snapshot.error}');
    
        if (snapshot.hasData) {
          var output = snapshot.data!.data();
          var value = output!['some_field']; // <-- Your value
          return Text('Value = $value');
        }
    
        return Center(child: CircularProgressIndicator());
      },
    )
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
26

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"));
Qiniso
  • 2,587
  • 1
  • 24
  • 30
thilinaj
  • 369
  • 3
  • 6
12

This is simple you can use a DOCUMENT SNAPSHOT

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

You can access its data using variable.data['FEILD_NAME']

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
6

Update FirebaseFirestore 12/2021

StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection('YOUR COLLECTION NAME')
              .doc(id) //ID OF DOCUMENT
              .snapshots(),
        builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return new CircularProgressIndicator();
        }
        var document = snapshot.data;
        return new Text(document["name"]);
     }
  );
}
jo3ght
  • 111
  • 1
  • 5
  • How can you take out a certain piece of information using this? Lets Say my collection is books Document is Harry Potter And under that i have table with Title Author Description, how would i print the author? – s3v3ns Feb 03 '21 at 10:02
  • Widget _buildBookItem(BuildContext context, int index, AsyncSnapshot snapshot) { final doc = snapshot.data.docs[index]; return Text(print(doc.author)); }; – jo3ght Feb 04 '21 at 04:26
3

This is what worked for me in 2021

      var userPhotos;
      Future<void> getPhoto(id) async {
        //query the user photo
        await FirebaseFirestore.instance.collection("users").doc(id).snapshots().listen((event) {
          setState(() {
            userPhotos = event.get("photoUrl");
            print(userPhotos);
          });
        });
      }
Ronny K
  • 3,641
  • 4
  • 33
  • 43
  • Is this a Future Query or a Stream Query? The return is a Future, but isn't the snapshots query for Stream? I'm confused. – dontknowhy Feb 04 '21 at 04:15
2

Use this code when you just want to fetch a document from firestore collection , to perform some operations on it, and not to display it using some widget (updated jan 2022 )

   fetchDoc() async {

   // enter here the path , from where you want to fetch the doc
   DocumentSnapshot pathData = await FirebaseFirestore.instance
       .collection('ProfileData')
       .doc(currentUser.uid)
       .get();

   if (pathData.exists) {
     Map<String, dynamic>? fetchDoc = pathData.data() as Map<String, dynamic>?;
     
     //Now use fetchDoc?['KEY_names'], to access the data from firestore, to perform operations , for eg
     controllerName.text = fetchDoc?['userName']


     // setState(() {});  // use only if needed
   }
}
hardkoded
  • 18,915
  • 3
  • 52
  • 64
Woah
  • 21
  • 2
1

Simple way :

StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection('YOUR COLLECTION NAME')
              .doc(id) //ID OF DOCUMENT
              .snapshots(),
        builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return new CircularProgressIndicator();
        }
        var document = snapshot.data;
        return new Text(document["name"]);
     }
  );
}
Kab Agouda
  • 6,309
  • 38
  • 32
1
        var  document = await FirebaseFirestore.instance.collection('Users').doc('CXvGTxT49NUoKi9gRt96ltvljz42').get();
        Map<String,dynamic>? value = document.data();
        print(value!['userId']);
avill blbn
  • 121
  • 1
  • 4
1

You can get the Firestore document by following code:

future FirebaseDocument() async{

    var variable = await FirebaseFirestore.instance.collection('Collection_name').doc('Document_Id').get();
    print(variable['field_name']); 
}
ClaudiaR
  • 3,108
  • 2
  • 13
  • 27
Umesh Rajput
  • 218
  • 1
  • 11
-3

Use this simple code:

Firestore.instance.collection("users").document().setData({
   "name":"Majeed Ahmed"
});
ZygD
  • 22,092
  • 39
  • 79
  • 102