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.
CodePudding user response:
If you see the return type of the get()
method that you are trying to call in doses.where('userID', isEqualTo: Auth().uID).get()
it is Future<QuerySnapshot<T>>
. There are two problems in your approach:
You are not awaiting the for 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:
static CollectionReference doses =
FirebaseFirestore.instance.collection('Doses');
Future<void> setDoseDetails(
TextEditingController endController,
TextEditingController startController,
TextEditingController doseController,
int noPills,
int doseRep) async {
QuerySnapshot dose =
await doses.where('userID', isEqualTo: Auth().uID).get();
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"];
}
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 for the response to return and then 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.
Hope that helps!
CodePudding user response:
This might work for you:
var dose =
await doses.where('userID', isEqualTo: Auth().uID).get();
var userData = dose.docs.first.data();
endController.text = userData['endDate'];
startController.text = userData['startDate'];
noPills = userData['noPills'];
doseController.text = userData['doseVal'];
doseRep = userData["doseRep"];