首页 > 解决方案 > 我需要一些关于 Flutter 和 dart 的未来异步调用的指导,有时事情会发生混乱

问题描述

下面的代码工作正常,因为它只返回一个简单的列表,但在某些情况下,我需要进行嵌套的 Firebase 调用,我无法让事情以正确的顺序发生,并且主要的 return 语句不完整。我可以做些什么来改进我的未来异步调用?

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

标签: flutterasynchronousdart

解决方案


最重要的事情; 不要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;
}

推荐阅读