【问题标题】:Flutter: Error: 'await' can only be used in 'async' or 'async*' methods. even thought the method is asyncFlutter:错误:“await”只能在“async”或“async*”方法中使用。甚至认为该方法是异步的
【发布时间】:2020-11-19 17:39:35
【问题描述】:

我有这个方法:

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 不起作用?

【问题讨论】:

  • 你调用的函数AppUser _user = await _getUser(document.id);怎么样?是异步的吗?
  • @JustCode,没有。这是一个snapshot.data.docs.map((DocumentSnapshot document){ 函数。我试着让它异步,但它返回Error: The argument type 'List&lt;Future&lt;UstaTile&gt;&gt;' can't be assigned to the parameter type 'List&lt;Widget&gt;'
  • 那就是问题所在,你试试_getUser(document.id).then((user){//code here})
  • @JustCode 我把快照放在then吗?
  • 这能回答你的问题吗? What is a Future and how do I use it?

标签: flutter


【解决方案1】:

_getUser() 是一个 asnyc 函数,但不是调用函数。 您收到的错误表明,await 用于非异步函数。 如果您在将调用函数转换为异步时遇到困难,请尝试使用then,如下所示。

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

总的来说,有两种解决方案

  1. 将调用函数转换为async
  2. 使用_getUser().then((user){});

【讨论】:

  • 因为 _getUser() 中的等待,运行时间太长,我得到 "Column's children must not contain any null values, but a null value was found at index 0"。我在document.get() 的getUser() 和_getUser(document.id).then((user) { 之前的一个打印语句以及它的内部。打印之前的那个,然后我得到一个错误,然后是里面的那个打印,最后是里面的 _getUser() 打印。
  • 您是否使用此回调中的数据来构建Column 小部件?在这种情况下,您必须使用未来的构建器或保持列构建过程,直到您收到来自异步回调的数据。
  • 如何保持列构建过程?
  • 借助 StatefulWidget 和单个布尔值,您可以将其归档。根据布尔值,您可以显示列数据或加载小部件。
  • 我正在尝试,但还是没有用。因为snapshot.data.docs.map((DocumentSnapshot document) { 在列内,所以不会被调用。
猜你喜欢
  • 2021-05-02
  • 2017-05-13
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2014-03-16
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多