【问题标题】:Troubleshooting FirebaseDatabaseFirebaseDatabase 故障排除
【发布时间】:2021-09-11 06:17:27
【问题描述】:

我是一名新的 Flutter 开发人员。目前正在从我的 FBDB 访问数据。 我调用了一个看起来像这样的函数。

void initState() {
  super.initState();
  Future<PartInfo> partInfo = HelperMethods.getPartDeets(widget.partid) 

}

HelperMethods 的代码如下所示。

 class HelperMethods {
  static Future<PartInfo> getPartDeets(String partid) async {
    PartInfo partInfo ;

    DatabaseReference partRef = FirebaseDatabase.instance.reference().child('parts/id0001');
    partRef.get().then((DataSnapshot snapshot) {
      if (snapshot.value != null) {
        partInfo = PartInfo.fromSnapshot(snapshot); //globalvar currentUserInfo
        print('part is ${partInfo.partname}');
        return partInfo;
      } else {
        print('snapshot is null') ;
      }
    });

    print(partInfo);
    return partInfo;
  }
}

我的数据库中的数据如下所示:

getPartDeets 方法中的打印语句永远不会被命中。并且 print(partInfo) 返回 null。有关如何解决此问题的任何提示?

【问题讨论】:

  • 代替partRef.get().then..试试partRef.once().then..

标签: flutter asynchronous firebase-realtime-database


【解决方案1】:

我通过将我的方法移动到我是 await 结果的 Future 方法来解决我的问题。还必须将 FutureBuilder 添加到我的堆栈中。如果您想了解更多信息,请发表评论。

【讨论】:

    【解决方案2】:

    您可能想尝试使用await,因为您已经标记了async 方法:

      static Future<PartInfo> getPartDeets(String partid) async {
        PartInfo partInfo ;
    
        DatabaseReference partRef = FirebaseDatabase.instance.reference().child('parts/id0001');
        DataSnapshot snapshot = await partRef.get();
        if (snapshot.value != null) {
          partInfo = PartInfo.fromSnapshot(snapshot); //globalvar currentUserInfo
          print('part is ${partInfo.partname}');
          return partInfo;
        } else {
          print('snapshot is null') ;
        }
    
        print(partInfo);
        return partInfo;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-15
      • 2010-11-30
      • 2012-02-18
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多