Home > Blockchain >  Do I have to use async/await when i use Firestore listen function?
Do I have to use async/await when i use Firestore listen function?

Time:08-25

i have the following listen 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

String myFirstValue = event.get('name');

in all cases i can get correct results .

i am totally confused . should i use await or not ? 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?

in other word : does the event that come from .listen((event) will have all values and there no need to use await in myFirstValue ?

CodePudding user response:

The event in your code is a 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.

That is different for DocumentReference.get(), which does return a Future. Using await here would unwrap the Future and give you the underlying DocumentSnapshot.

  • Related