【问题标题】:Not sure to which statement the await keyword needs to be applied in Flutter or Dart不确定在 Flutter 或 Dart 中需要将 await 关键字应用于哪个语句
【发布时间】:2020-11-18 19:54:46
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore flutter-futurebuilder


    【解决方案1】:

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

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

    get() 方法返回一个Future&lt;QuerySnapshot&gt;,因此而不是使用then(),它接受一个回调,当未来完成时将被调用。

    阅读以下指南:

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

    【讨论】:

    • 非常感谢@Peter Haddad,TBH 两天前我还在您的频道上观看视频,也感谢您提供的精彩内容 :)
    • 我不确定它是 YouTube 频道还是 Udemy 课程。我一直在四处学习 Flutter。
    • 你好@Peter Haddad,我记得我在Medium medium.com/@peterhaddad阅读了你的文章
    猜你喜欢
    • 2015-06-08
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多