如何将未来的 return 值存储在变量中?

how can i store the return value of a future in a variable?

我想知道如何在应用程序状态的变量中存储 flutter 应用程序中未来的 return 值? 例如 : List usernames = await AuthMethods().getCurrentUserInvitations() 其中方法 getCurrentUserInvitations return 是一个列表。 我只得到实例而不是未来的实际 return。

Future<List> getCurrentUserInvitations() async {
    List usernames = [];
    try {
      var snap = await _firestore
          .collection("users")
          .doc(_auth.currentUser!.uid)
          .get();
      print(snap.data()!["invitedBy"]);
      snap.data()!["invitedBy"].forEach((invitedById) async {
        try {
          var snap =
              await _firestore.collection("users").doc(invitedById).get();
          print(snap.data()!["username"]);
          usernames.add(snap.data()!["username"]);
        } catch (e) {
          print(e.toString());
        }
      });
    } catch (e) {
      print(e.toString());
    }
    return usernames;
  }

添加了方法中的代码

如果您只是想将未来存储到一个变量中,有一种非常直接的方法可以做到这一点。在您的代码中,将其更改为

Future<List> usernames = AuthMethods().getCurrentUserInvitations()

然后,当您想要访问 Future 中返回的数据时,您将不得不等待 Future 完成。比如要计算List的长度,做

Future<List> usernames = AuthMethods().getCurrentUserInvitations()
.
.
.
   /* ... Code that doesn't need value of usernames ... */
.
.
.
/* Then when you want the actual values, */
List actualUsernames = await usernames;
print(actualUsernames.length);