【发布时间】:2020-04-02 19:31:21
【问题描述】:
我偶然发现了一个奇怪的问题。
以下函数获取 Firestore 文档并将其返回,以便其他函数可以访问它的数据
Future getCountRequests() async {
try{
return await _countReference.document('Requests').get();
} catch(e){
print(e.toString());
}
}
这就是使用它的数据的函数。
int _countRequest() {
int toReturn;
CounterService().getCountRequests().then(
(doc) {
//print('Item in question: $doc, information from document ${doc.data}');
//this line prints correctly Instance of DocumentReference and {"amount" : 6}
toReturn = doc.data['amount'];
}
);
return toReturn;
}
当我运行代码时,我在屏幕上收到一条错误消息,指出我正在使用的 AnimatedList 从 _countRequest() 函数接收到 null。
在这一行打断有助于我理解这个块被完全跳过
CounterService().getCountRequests().then( ...
但是,当我在这一行上打断时,它表明块内的代码有效,并且确实通过getCountRequests() 函数接收到该文档。
toReturn = doc.data['amount'];
我的问题是,是什么导致 .then 块被跳过导致函数返回 null?
【问题讨论】:
-
您应该在要获取的未来函数之前添加
await。 -
请参阅这些指南 [1] 以了解“等待”的一些示例。 [1]dart.dev/codelabs/…
-
是的,我访问了这些页面。根据我从其他几篇文章的理解,“then”函数应该可以从异步函数中获取值并使其在同步函数中可用。这就是我在这里尝试的,所以这让我想知道我做错了什么。
-
then()方法在您从_countRequest方法返回后被调用,这就是您得到null的原因,因为toReturn没有设置为它的任何值声明 -
感谢您的回复,我明天会尝试您的解决方案,如果它有效,请告诉您。
标签: asynchronous flutter dart google-cloud-firestore future