【问题标题】:Flutter Futurebuilder not returning anythingFlutter Futurebuilder没有返回任何东西
【发布时间】:2020-05-17 10:17:14
【问题描述】:

我有一个 Flutter 中的 Futurebuilder,但它从不返回任何东西。

如下所示,我有一个 Futurebuilder,它调用了一个名为 getGamesLost 的方法。如果没有数据,它会显示一个加载指示器。

  FirestoreUserProfile firestoreUserProfile = new FirestoreUserProfile();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: firestoreUserProfile.getGamesLost(),
        builder: (BuildContext context, AsyncSnapshot<int> userProfileData) {
          if(userProfileData.hasData) {
             print(userProfileData);
          }
          else {
            return Styling.loadingIndicator;
          }
        }
    );

我的问题是永远没有数据。下面是 getGamesLost 方法。

  Future<int> getGamesLost() async {
    return await firestoreCollectionReference
        .document(FirebaseUserData.currentFirebaseUser.email)
        .snapshots().forEach((userData) {
          return userData.data[describeEnum(fieldNames.profile)][describeEnum(fieldNames.gamesLost)];
    });
  }

由于某种原因,futurebuilder 调用的 getGamesLost 永远不会完成。我可以在最后一次返回之前打印userData 的值,这意味着实际上有数据从firebase 返回,但好像该方法实际上从未返回,futurebuilder 只是一直在等待。

【问题讨论】:

  • 没有错误,我也把它从void改成了int。如果我将其更改为 String 或任何其他数据类型,它会显示错误,但不会无效。

标签: asynchronous flutter dart promise


【解决方案1】:

这是因为您正在使用snapshots() 返回的流来获取数据并对其进行迭代。此流保持活动状态并侦听任何实时数据更新。这里的forEach 函数会给你一个Future,但它只有在snapshots() 返回的Stream 完成时才会完成。因此,Future 永远不会完成。

如果您只想要文档中的值,只需像这样使用它。

// The `get` method instead of `snapshots` just fetches the doc at this instance and would not listen for updates
Future<int> getGamesLost() async {
  return await firestoreCollectionReference
      .document(FirebaseUserData.currentFirebaseUser.email)
      .get() 
      .then((DocumentSnapshot userData) {
    return userData.data[describeEnum(fieldNames.profile)]
        [describeEnum(fieldNames.gamesLost)];
  });
}

希望有帮助!

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 2015-02-11
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2014-04-28
    相关资源
    最近更新 更多