0

我在 await 关键字下方出现绿色漩涡状线条。

当我将鼠标悬停在绿色漩涡线上时,它会显示'await' applied to 'Query', which is not a 'Future'

我不确定需要将 await 关键字应用于哪个语句。

如果不对方法应用 await/async 和 Future,调用方法不会等待此方法完成并继续执行其余代码,因此返回空值。

请在下面找到有问题的代码:

Future<List<ContData>> readCC(String tID) async {
    List<ContData> conList = [];
    try {
      final conCollection = await FirebaseFirestore.instance
          .collection('CC')
          .where('conID', isEqualTo: tID);

      await conCollection.snapshots().listen((snapshot) {
        var tc = snapshot.docs[0].data()['con'];
        ContData con;
        for (var t in tc) {
          con = ContData.fromMap(data: t);
          print(con);
          final conType = con.conType;
          final conText = con.conText;
          final conCodeCaption = con.conCodeCaption;
          final conCodeText = con.conCodeText;
          final conCodeOutput = con.conCodeOutput;
          final conImageFilename = con.conImageFilename;
          final conImageCaption = con.conImageCaption;
          final conImageCredit = con.conImageCredit;
          final conImageCreditLink = con.conImageCreditLink;
          final conAnchorText = con.conAnchorText;
          final conAnchorLink = con.conAnchorLink;
          final ContData = ContData(
              conType: conType,
              conText: conText,
              conCodeCaption: conCodeCaption,
              conCodeText: conCodeText,
              conCodeOutput: conCodeOutput,
              conImageFilename: conImageFilename,
              conImageCaption: conImageCaption,
              conImageCredit: conImageCredit,
              conImageCreditLink: conImageCreditLink,
              conAnchorText: conAnchorText,
              conAnchorLink: conAnchorLink);
        }
      });
    } catch (e) {
      print(e.toString());
    }
    return conList;
  }

非常感谢您的宝贵时间和提前帮助!

4

1 回答 1

1

您只能添加await到返回 a 的方法,Future例如:

final conCollection = await FirebaseFirestore.instance
          .collection('CC')
          .where('conID', isEqualTo: tID).get();

因此,该方法get()返回 aFuture<QuerySnapshot>而不是 using then()which 接受一个回调,该回调将在未来完成时调用。

阅读以下指南:

https://dart.dev/codelabs/async-await

于 2020-11-18T20:17:36.277 回答