Flutter: Error: 'await' can only be used in 'async' or 'async*' methods. even thought the method is async

Viewed 593

I have this method:

Future<AppUser> _getUser(String documentId) async {
    var document = await firestore.collection('customers').doc(documentId);
    document.get().then((DocumentSnapshot documentSnapshot) {
          print(documentSnapshot.data());
    });
    AppUser bruceUser = AppUser(userId: 'user006',);

    return bruceUser;   
}

And below it, I have a variable that uses this method:

AppUser _user = await _getUser(document.id);

However, this returns the following error:

Error: 'await' can only be used in 'async' or 'async*' methods.

What am I doing wrong here? I don't want to change _user to Future, because it will complicate the code further, so why doesn't the await work?

1 Answers

_getUser() is an asnyc function but not the calling function. The error you are getting states that, await was used in a non-async function. If you have difficulty in converting the caller function to async, try using then as follows.

snapshot.data.docs.map((DocumentSnapshot document) {
    _getUser(document.id).then((user) {
          //code here
    });
}

In summary, there are two solutions for this

  1. Convert the caller function to async.
  2. Use _getUser().then((user){});
Related