flutter - 在未来的异步调用中,我需要一些指导,包括 flutter 和 Dart ,有时情况会发生困惑

标签 flutter asynchronous dart

以下代码可以正常工作,因为它仅返回一个简单列表,但是在某些情况下,我需要执行嵌套Firebase调用,因此无法按正确的顺序进行操作,并且主return语句不完整。我该怎么做才能改善我的 future 异步 call ?

Future<List<MyNotification>> getNotifications() async {
    var uid = await FirebaseAuth.instance.currentUser();

    List<MyNotification> tempNots = await Firestore.instance
        .collection("notifications")
        .where("targetUsers", arrayContains: uid.uid)
        .getDocuments()
        .then((x) {
      List<MyNotification> tempTempNots = [];
      if (x.documents.isNotEmpty) {
        for (var not in x.documents) {
          tempTempNots.add(MyNotification.fromMap(not));
        }
      }
      return tempTempNots = [];
    });
    return tempNots;
  }

最佳答案

最重要的事情;不要在异步函数中使用then。我这样修改了您的代码;

Future<List<MyNotification>> getNotifications() async {
  // Using the type definition is better.
  FirebaseUser user = await FirebaseAuth.instance.currentUser();

  // The return type of getDocuments is a QuerySnapshot
  QuerySnapshot querySnapshot = await Firestore.instance
      .collection("notifications")
      .where("targetUsers", arrayContains: user.uid)
      .getDocuments();

  List<MyNotification> tempTempNots = [];

  if (querySnapshot.documents.isNotEmpty) {
    for (DocumentSnapshot not in querySnapshot.documents) {
      tempTempNots.add(MyNotification.fromMap(not));
    }
  }
 return tempTempNots;
}

关于flutter - 在未来的异步调用中,我需要一些指导,包括 flutter 和 Dart ,有时情况会发生困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61278809/

相关文章:

flutter 将顶部和底部小部件添加到列表 GridView.builder

javascript - 使用 Jasmine 进行异步回调测试

c# - CA2007 与 .NET Core 应用程序相关吗?

c++ - dart 加密解密 AES 示例

flutter - 在 android studio 中运行 flutter 项目时出现 'Unexpected Kernel SDK Version' 错误

dart - 在底部工作表中点击项目时显示 snackbar

dart - 抽屉导航不适用于屏幕内的屏幕

dart - 从 AngularDart 0.14.0 迁移到 1.0.0

ios - 在硬件上运行时没有可用的audioEngine输入 channel

c# - 即使使用 ConfigureAwait(false),在 WebAPI 中同步调用异步方法也会死锁