My Flutter app is executing the code inside the .then() function after everything is finished. I thought that this function was used to wait for the code to be executed. Am I understanding something wrong about dart?
This is my code:
static Future<List<Quiz>> getUserQuizzes(
{FirebaseFirestore? firestore}) async {
if (firestore == null) {
firestore = FirebaseFirestore.instance;
}
List<Quiz> quizzes = [];
/// Get the the id's of all quizzes whose creatorID is the current user's id
await firestore
.collection('quizzes')
.where('creatorID', isEqualTo: getCurrentUserID())
.get()
.then((QuerySnapshot querySnapshot) {
print('print 1: ${querySnapshot.docs.length}');
querySnapshot.docs.forEach((doc) async {
print('print inside forEach');
Quiz? tempQuiz;
await Quiz().retrieveQuizFromId(id: doc.id).then((value) {
tempQuiz = value;
quizzes.add(tempQuiz!);
print('print inside then: ${quizzes.length}');
});
});
});
print('print 2: ${quizzes.length}');
return quizzes;
}
}
And this is the console output:
Performing hot reload...
Syncing files to device iPhone 14 Pro Max...
Reloaded 1 of 1330 libraries in 385ms (compile: 61 ms, reload: 147 ms, reassemble: 128 ms).
flutter: print 1: 5
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print inside forEach
flutter: print 2: 0
flutter: print inside then: 1
flutter: print inside then: 2
flutter: print inside then: 3
flutter: print inside then: 4
flutter: print inside then: 5