Problem with Flutter and Firestore, program tries to process data which was not retrieved yet

Viewed 13

Program tries to process data which was not retrieved yet. I put plenty of displays to verify that this indeed happens.

This my code inside Stateless widget: ....

Print(“before calling getDocs()”)
getDocs(); // retrieves data from Firestore
Print(“after calling getDocs()”)

data retrieved by getDocs() function is processed ....

getDocs() is defined outside any class or Widget

void getDocs() async {
    print("******inside getDocs() start*****************");
    await FirebaseFirestore.instance.collection('Spanish').get().then((snapshot) {
         print("********inside getDocs() 1"); 
....
    print("******inside getDocs() end*****************");

And this is what I see on the log:

before calling getDocs()
******inside getDocs() start*****************
******inside getDocs() end*****************
after calling getDocs()
********inside getDocs() 1

The result is an error - program tries to process data which was not retrieved yet. The other display from getDocs() shows the data was received correctly. Question - how to prevent program to process data when the data is not available yet?

1 Answers

Since getDocs is declared as an async function, you need to call it with await if you want to wait until it's done before continuing processing:

So:

await getDocs();

If you're in a context where you can't use await, you can attach a then handler instead:

getDocs().then(() {
  ... do whatever needs to happen after getDocs() is done here
})
Related