The await expression can only be used in an async function
Solution 1
your main function for that line is that passed to listen of onAuthStateChanged.this function should be async too like below
_auth.onAuthStateChanged.listen((firebaseUser) async{
Solution 2
If you are calling an async function, your calling function should be async too.
Add the async keyword to your function. Change:
void main (List<String> arguments)
to:
void main (List<String> arguments) async
Examples:
Future<void> main (List<String> arguments) async {
var done = await readFileByteByByte(); // perform long operation
}
Future<void> main(List<String> arguments) {
readFileByteByByte().then((done) {
print('done');
});
print('waiting...');
print('do something else while waiting...');
}
August W Danowski
By day, I do tech support and web design, by night I am teaching myself to program the latest and greatest iOS app.
Updated on December 17, 2022Comments
-
August W Danowski over 1 year
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? -
August W Danowski over 4 yearsThank you. Now that seems painfully obvious.