[英]Do I have to use async/await when i use Firestore listen function?
我有以下听 function
FirebaseFirestore.instance.collection('users').doc(widget.userId).snapshots().listen((event)
async{
if(!event.metadata.isFromCache){
String myFirstValue = await event.get('name');
// here i have many local operations that depends on `myFirstValue` Constantly as the
document changes
}
});
在前面的代码中,经过多次测试,我注意到我可以使用await
并且我不能像下面这样使用它
String myFirstValue = event.get('name');
在所有情况下,我都能得到正确的结果。
我完全糊涂了。 我应该使用await
还是不使用? 有什么更好的用途? 如果我不使用等待,是否有某些情况会导致我的操作出现错误,这取决于我的myFirstValue
?
换句话说:来自.listen((event)
event
事件是否将具有所有值并且不需要在myFirstValue
中使用 await ?
您代码中的event
是DocumentSnapshot
。 如果我们查看参考文档DocumentSnapshot.get
没有返回Future
,那么调用它时就不需要使用await
了。
这与DocumentReference.get()
不同,它确实返回了Future
。 在此处使用await
将打开Future
并为您提供底层DocumentSnapshot
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.