[英]Do I have to use async/await when i use Firestore listen function?
i have the following 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
}
});
in the previous code, after many tests i noticed that i can use await
and also i can not use it like following在前面的代码中,经过多次测试,我注意到我可以使用
await
并且我不能像下面这样使用它
String myFirstValue = event.get('name');
in all cases i can get correct results.在所有情况下,我都能得到正确的结果。
i am totally confused.我完全糊涂了。 should i use
await
or not?我应该使用
await
还是不使用? what is the better use?有什么更好的用途? is there some cases leads me to have errors in my operations that depends on my
myFirstValue
if i didn't use await?如果我不使用等待,是否有某些情况会导致我的操作出现错误,这取决于我的
myFirstValue
?
in other word: does the event
that come from .listen((event)
will have all values and there no need to use await in myFirstValue
?换句话说:来自
.listen((event)
event
事件是否将具有所有值并且不需要在myFirstValue
中使用 await ?
The event
in your code is a DocumentSnapshot
.您代码中的
event
是DocumentSnapshot
。 If we check the reference documentation DocumentSnapshot.get
does not return a Future
, so there's no need to use await
when calling it.如果我们查看参考文档
DocumentSnapshot.get
没有返回Future
,那么调用它时就不需要使用await
了。
That is different for DocumentReference.get()
, which does return a Future
.这与
DocumentReference.get()
不同,它确实返回了Future
。 Using await
here would unwrap the Future
and give you the underlying DocumentSnapshot
.在此处使用
await
将打开Future
并为您提供底层DocumentSnapshot
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.