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!
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.
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");
}
});
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']);
}
}
)
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'];
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With