Reputation: 1482
I have a function that retrieve a List of data as a Future.
final CollectionReference _departmentHoursCollection =
FirebaseFirestore.instance.collection('departmentsHours');
Future<List<DepartmentHour>> isUnfinishedGK(List<String> sites) async {
sites.asMap().forEach((key, value) async {
QuerySnapshot departmentsHoursSnapshot = await _departmentHoursCollection
.where('siteName', isEqualTo: value)
.where('justification', isEqualTo: 'working')
.get();
if (departmentsHoursSnapshot.docs.isNotEmpty) {
departmentsHoursSnapshot.docs.asMap().forEach((key, value) async {
var document = await value.reference.get();
print(document.data());
_temporal.add(DepartmentHour.fromMap(document.data()));
});
}
});
print("size: ${_temporal.length}");
return _temporal;
}
however when i print size at the end, it keeps showing:
I/flutter (20592): size: 0
But the data is being fetched and added to the variable: _temporal:
I/flutter (20592): {globalTime: 24304, endHour: 06:00, startedTime: Timestamp(seconds=1602329908, nanoseconds=453000000), departmentHourDetails: [{globalTime: 24300, endJobTime: Timestamp(seconds=1602354212, nanoseconds=456000000), department: Grind Room, startJobTime: Timestamp(seconds=1602329911, nanoseconds=766000000)}, {globalTime: 24299, endJobTime: Timestamp(seconds=1602354212, nanoseconds=456000000), department: Main Production, startJobTime: Timestamp(seconds=1602329913, nanoseconds=94000000)}], startHour: 22:00, scheduleDate: Timestamp(seconds=1602306000, nanoseconds=0), finishedTime: Timestamp(seconds=1602329908, nanoseconds=453000000), siteName: SMD, justification: working}
anyone knows how to return the List with the fetched data instead of returning a [].
Upvotes: 0
Views: 145
Reputation: 3469
To solve the problem you can use Future.forEach(), that waits for each Future to be completed before moving to the next element, as you can see here.
Example:
Future<List<String>> myFuture(List<String> names) async {
List<String> newNames = [];
await Future.forEach(names, (name) async {
await Future.delayed(Duration(seconds: 2), () {
newNames.add(name);
});
});
return newNames;
}
Upvotes: 1