1
votes

Scenario explained: Using: import 'package:cloud_firestore/cloud_firestore.dart';

Cloud Firestore: a Collection 'sessionsLog', containing documents with the following fields: 'sessionId' a String 'isClosed' a bool 'locationId' a String and some other fields ...

I want to retrieve all documents with a false bool for 'isClosed', only once, and then perform some actions. Therefore I chose to use a FutureBuilder (not a streambuilder), what I did:

    FutureBuilder(
    future: Firestore.instance.collection('sessionsLog')
    .where('isClosed', isEqualTo: false).getDocuments();
    builder: (ctx, sessionSnapshot) {
    return  RaisedButton(
    child: Text('Search'),
    onPressed: () async {
    //some other code here, that needs async I added on top

    if (sessionSnapshot.connectionState !=
                        ConnectionState.done) {
                      return CircularProgressIndicator();
                    }
    if (!sessionSnapshot.hasData) {i should 
                      print('nothing to show here');
                    }else {
    //the below line of code is wrong, it could be print / or Text / or any other widget
    //I've just added it for the sake of an example.
    print(sessionSnapshot.data.documents[0]['parkingLocationName']);}});}),

The above code is not working, I've just created it for a simple code result, to just be able to print values I am retrieving, so please don't fix something in my code.

Also noting that, in my code logic, there will always be once single document with 'isClosed' = false. So, I should always receive one single document.

But If it differs, please give me 2 examples, one if retrieved data contains 1 single document and another if there could be several documents and therefore how would I iterate in the data.

I just want the correct way to be able to READ/access the data I am receiving, whether to print the fields info, or display them in a text. anything, but how would I do that, in the exact explained above scenarios.

Would really appreciate a simple sample example based on my code scenario.

1
I am not sure about the first problem you are facing here but if there could be multiple documents returned by your query and you only care about one, you should probably look at limit and orderBy in the Firestore documentation.Tom Bailey
Hi Tom, thanks mate. But this is not about how to filter. My aim is as to how to read the fields data, how to access them. Whether receiving a single or many documents.YaGeorge

1 Answers

2
votes

I would do this without using a FutureBuilder:

return Scaffold(
  body: Container(
    child: Center(
      child: RaisedButton(
          child: Text('Search'),
          onPressed: () {
            searchForDocs();
          }),
    ),
  ),
);

Future:

void searchForDocs() async {
await Firestore.instance
    .collection('sessionsLog')
    .where('isClosed', isEqualTo: false)
    .getDocuments()
    .then((snapshot) {
  if (snapshot.documents != null && snapshot.documents.length > 0) {
    snapshot.documents.forEach(
      (document) {
        print(document['parkingLocationName']);
      },
    );
  } else {
    print('No Documents Found');
  }
});}

My output:

I/flutter ( 2933): Example
I/flutter ( 2933): Example2`

Here is the code if you would still like to use a FutureBuilder:

return Scaffold(
  body: Container(
    child: Center(
      child: FutureBuilder(
          future: Firestore.instance
              .collection('sessionsLog')
              .where('isClosed', isEqualTo: false)
              .getDocuments(),
          builder: (context, snapshot) {
            return RaisedButton(
                child: Text('Search'),
                onPressed: () {
                  if (!snapshot.hasData) {
                    print('Nothing to show here');
                  } else {
                    if (snapshot.data.documents != null &&
                        snapshot.data.documents.length > 0) {
                      List<DocumentSnapshot> documents =
                          snapshot.data.documents;
                      documents.forEach((document) {
                        print(document['parkingLocationName']);
                      });
                    }
                  }
                });
          }),
    ),
  ),
);

I get the same output as the previous solution:

I/flutter ( 2933): Example
I/flutter ( 2933): Example2`

Here is Firestore to verify: Firestore