Reputation: 31
im trying to randomly get documents from firebase. Since .where(FieldPath.documentId, whereIn: element)
only supports lists of 10 elements i split my list to sublists and run each query based on the sublists. When result from each query is returned i try adding them to an List<DocumentSnapshot<Object?>> results = [];
This List is then returned and my problem is that the screen displays error, but if i reload the screen it works. I think the problem is that my function wants to return
Future<List<DocumentSnapshot>> getBeerPongCards1() async {
But my List is List<DocumentSnapshot<Object?>> results = [];
Future<List<DocumentSnapshot>> getBeerPongCards1() async {
List<DocumentSnapshot<Object?>> results = [];
List<String> IdList = List<String>.generate(20, (counter) => "$counter");
IdList.shuffle();
List<List<String>> subList = [];
for (var i = 0; i < IdList.length; i += 10) {
subList.add(
IdList.sublist(i, i + 10 > IdList.length ? IdList.length : i + 10));
}
subList.forEach((element) async {
await FirebaseFirestore.instance
.collection('beerpong1')
.where(FieldPath.documentId, whereIn: element)
.limit(10)
.get()
.then((value) async {
results.addAll(value.docs);
});
});
return results;
}
I dont know if my question made any sense but im thankful for any help:D
Upvotes: 2
Views: 414
Reputation: 4089
The issue is likely that when you use sublist.forEach
, that for loop is not awaited, so you return an empty list (in any case, that should be handled in a graceful way for the user).
Instead of using a .forEach
function, use a regular for loop - That way, each element will be awaited properly, and the list will be populated when the function returns:
for (final element in subList) {
await FirebaseFirestore.instance
.collection('beerpong1')
.where(FieldPath.documentId, whereIn: element)
.limit(10)
.get()
.then((value) async {
results.addAll(value.docs);
});
}
Upvotes: 1