Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from firestore document fields in flutter?

I'm trying to test firestore in my flutter-app but I can't really load the data as expected.

This is how I get the data:

 Firestore.instance
        .collection('Test')
        .document('test')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot

      print('Values from db: $ds');
    });

And print-statement output: flutter: Values from db: Instance of 'DocumentSnapshot'.

I also tried following, without success:

Firestore.instance.collection('Test').document('test').get().then((data) {
  // use ds as a snapshot

  if (data.documentID.length > 0) {
    setState(() {
      stackOver = data.documentID;
      print(stackOver);
    });
  }
});

Output here is only the documentID-name..

So, how could I get the field-values from firestore?

Best regards!

like image 959
Rusben Wladiskoz Avatar asked Jul 18 '19 11:07

Rusben Wladiskoz


People also ask

How do I get data from a firestore document?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.


3 Answers

Try this:

final String _collection = 'collectionName';
final Firestore _fireStore = Firestore.instance;

getData() async {
  return await _fireStore.collection(_collection).getDocuments();
}

getData().then((val){
    if(val.documents.length > 0){
        print(val.documents[0].data["field"]);
    }
    else{
        print("Not Found");
    }
});
like image 110
Muhammad Noman Avatar answered Oct 20 '22 16:10

Muhammad Noman


I faced a similar problem and solved it this way:

Stream<DocumentSnapshot> provideDocumentFieldStream() {
    return Firestore.instance
        .collection('collection')
        .document('document')
        .snapshots();
}

After that, I used a StreamBuilder to consume the method created above:

StreamBuilder<DocumentSnapshot>(
    stream: provideDocumentFieldStream(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasData) {
            //snapshot -> AsyncSnapshot of DocumentSnapshot
            //snapshot.data -> DocumentSnapshot
            //snapshot.data.data -> Map of fields that you need :)

            Map<String, dynamic> documentFields = snapshot.data.data;
            //TODO Okay, now you can use documentFields (json) as needed

            return Text(documentFields['field_that_i_need']);
        }
    }
)
like image 32
Rodrigo Castro Avatar answered Oct 20 '22 18:10

Rodrigo Castro


Null safe code:

  • One time reading of the data:

    var collection = FirebaseFirestore.instance.collection('users');
    var docSnapshot = await collection.doc('some_id').get();
    if (docSnapshot.exists) {
      Map<String, dynamic> data = docSnapshot.data()!;
    
      // You can then retrieve the value from the Map like this:
      var name = data['name'];
    }
    
  • Continually listening for the data:

    var collection = FirebaseFirestore.instance.collection('users');
    collection.doc('some_id').snapshots().listen((docSnapshot) {
      if (docSnapshot.exists) {
        Map<String, dynamic> data = docSnapshot.data()!;
    
        // You can then retrieve the value from the Map like this:
        var name = data['name'];
      }
    });
    
like image 41
CopsOnRoad Avatar answered Oct 20 '22 18:10

CopsOnRoad