Flutter : 오류 : 'await'는 'async'또는 'async *'메서드에서만 사용할 수 있습니다. 방법이 비동기 적이라고 생각했습니다.

Nov 20 2020

이 방법이 있습니다.

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;   
}

그 아래에는이 방법을 사용하는 변수가 있습니다.

AppUser _user = await _getUser(document.id);

그러나 다음 오류가 반환됩니다.

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

내가 여기서 뭘 잘못하고 있니? _user를 Future로 변경하고 싶지 않습니다. 코드가 더 복잡해지기 때문에 왜 await가 작동하지 않습니까?

답변

1 JustCode Nov 20 2020 at 00:57

_getUser()asnyc 함수이지만 호출 함수는 아닙니다. await비 비동기 함수에서 사용 된 상태를 얻는 오류 입니다. 호출자 함수를 비동기로 변환하는 데 어려움이 있다면 then다음과 같이 사용해보십시오 .

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

요약하면 두 가지 해결책이 있습니다.

  1. 호출자 함수를 async.
  2. 사용하다 _getUser().then((user){});