I am trying to load some data from Firestore when the user logs in and need to wait until the data is loaded before continuing. However, my efforts to await the results are not working.
Future<bool> userListener() async {
_auth.onAuthStateChanged.listen((firebaseUser) {
bool isDone = false;
if (firebaseUser != null) {
isDone = await loadUserData(firebaseUser); // This line is killing me!!
return isDone;
} else {
return false;
}
}, onError: (error) {
print('error in UserListener: $error');
});
}
Future<bool> loadUserData(FirebaseUser user) async {
Firestore database = Firestore();
DocumentReference data = database.collection('userData').document(user.uid);
try {
DocumentSnapshot myQuery = await data.get();
theNumber = myQuery.data['theNumber'];
return true;
} on PlatformException catch (e) {
print(e);
return false;
}
}
I get a lovely error from the line:
isDone = await loadUserData(firebaseUser);
that "the await expression can only be used in an async function".
I'm not sure how these functions could get any more async. Further, if I don't add await
then I am told that a Future can't be assigned to a bool, which makes perfect sense, and suggest to me that my function is, in fact, async.
Why can't I await the results of my loadUserData
function?