static CollectionReference doses =
FirebaseFirestore.instance.collection('Doses');
void setDoseDetails(
TextEditingController endController,
TextEditingController startController,
TextEditingController doseController,
int noPills,
int doseRep) {
var dose =
doses.where('userID', isEqualTo: Auth().uID).get() as DocumentSnapshot;
Map<String, dynamic> userData = dose as Map<String, dynamic>;
endController.text = userData['endDate'];
startController.text = userData['startDate'];
noPills = userData['noPills'];
doseController.text = userData['doseVal'];
doseRep = userData["doseRep"];
}
I’m trying to retrieve data from Firebase using this code and it’s not working.
2
Answers
If you see the return type of the
get()
method that you are trying to call indoses.where('userID', isEqualTo: Auth().uID).get()
it isFuture<QuerySnapshot<T>>
. There are two problems in your approach:You are not awaiting the result of
doses.where('userID', isEqualTo: Auth().uID).get()
.You are forcefully type-casting a QuerySnapshot into a DocumentSnapshot. If
doses.where('userID', isEqualTo: Auth().uID).get()
after awaiting, returns a QuerySnapshot, the variable holding that value should also be of the type QuerySnapshot.Here is what you can do instead:
If you notice in the solution above,
I have changed the return type of
setDoseDetails
because it can’t be justvoid
and has to beFuture<void>
because you are dealing with futures.I have put an
await
keyword in front of thedoses.where('userID', isEqualTo: Auth().uID).get()
. This will allow the response to return and be assigned to the variabledose
.To read more about futures I would suggest going through https://api.flutter.dev/flutter/dart-async/Future-class.html.
I hope that helps!
This might work for you: