Search code examples
firebasedartfluttergoogle-cloud-firestorequerying

Query a single document from Firestore in Flutter (cloud_firestore Plugin)


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.


Solution

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