Reputation: 123
So, I have learned how to create and update documents in a firebase firestore cloud, however I am having trouble reading data. Attached is my code for finding the value of the 'photourl' field:
String photoy;
Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
photoy=ds.data['photourl'];
});
setState(() {
photourldisplay=photoy;
});
However, upon running my program, the photourldisplay value seems to not have changed and remains null upon running. This means that something is askew with my code that retrieves this "photourl" field. Can someone help me retrieve a field in a firebase document?
Upvotes: 0
Views: 12387
Reputation: 1460
Your code is good you just have to await for the result:
void yourVoid () async {
String photoy;
await Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
photoy=ds.data['photourl'];
});
setState(() {
photourldisplay=photoy;
});
}
EDIT: as @Doug Stevenson said, there is two propers solutions:
void yourVoid () async {
DocumentSnapshot ds = await Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get();
String photoy = ds.data['photourl'];
setState(() {
photourldisplay=photoy;
});
}
and:
Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
photoy=ds.data['photourl'];
setState(() {
photourldisplay=photoy;
});
});
Upvotes: 2
Reputation: 317913
photoy
does not contain the value you expect because Firestore queries are asynchronous. The get() returns immediately, and the callback is invoked some time later, after the query completes. There is no guarantee how long a query might take. If you want to pass the value of photoy
to something else, you will have to wait until the callback completes by making use of it only within that callback.
Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
photoy=ds.data['photourl'];
setState(() {
photourldisplay=photoy;
});
});
Upvotes: 5