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

blandaadrian picture blandaadrian · Nov 28, 2018 · Viewed 49.1k times · Source

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.

Answer

Alex Mamo picture Alex Mamo · Nov 28, 2018

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.