0

In Dart/Flutter and learning Firebase Firestore... I'm using the following method to test before creating UI:

_testFireStore() async {
  var result = Firestore.instance
      .collection('users')
      .where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1')
      .snapshots();

  await for (var snapshot in result) {
    for (var user in snapshot.documents) {
      print('main.DEBUG: ' + user.data.toString());
    }
  }
}

It works as expected -- the print statement is executed initially, but also subsequently in real-time every time any field is updated in the document in the Firestore database.

How can this code be changed such that the snapshot is only retrieved once -- not "subscribed/listened" to... and thus we don't waste bandwidth on unwanted/unneeded data and the print statement is only executed once?

Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100
  • Yes, thanks. I think both answers work, but Doug's was first. – Nerdy Bunz Mar 04 '20 at 22:48
  • 1
    For more Answers, visit my (older) question https://stackoverflow.com/questions/53517382/query-a-single-document-from-firestore-in-flutter-cloud-firestore-plugin – blandaadrian Oct 03 '22 at 13:53

2 Answers2

1

Firestore.instance.collection(...).where(...) returns a Query object. It has a method called getDocuments() that executes the query and gives you a Future with a single set of results.

var query = Firestore.instance
    .collection('users')
    .where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1');
query.getDocuments().then((QuerySnapshot snapshot) {
    // handle the results here
})

Or use await to get the QuerySnapshot, since getDocumets() returns a Future.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I tried putting a print statement where the ' // handle ' comment is but it is never executed. also tried putting 'await' prior to query.getDoc... but same result. – Nerdy Bunz Feb 28 '20 at 03:22
0

Use getDocuments(), to retrieve all the documents once:

_testFireStore() async {
  var result = await Firestore.instance
      .collection('users')
      .where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1')
      .getDocuments();
      print(result.documents.toString());
}
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134