9

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?

2 Answers 2

6

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{
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Now that seems painfully obvious.
4

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...');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.