我是一个新的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。关于如何解决这个问题,有什么建议吗?
发布于 2021-06-29 11:59:56
假设您已经将方法标记为async,那么您可能希望尝试使用await:
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;
}发布于 2021-06-29 14:31:52
我修复了我的问题,将我的方法移动到一个我是await results的Future方法中。我还必须在我的堆栈中添加一个FutureBuilder。如果你想了解更多信息,请发表评论。
https://stackoverflow.com/questions/68171890
复制相似问题