Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to iterate over future<list> in flutter

I would like to iterate over the the Future<list> but get errors if I try using for loops or if I try setting it as List.

Is there any other way of looping over each element in the list:

Future<List> getDailyTask(DateTime date) async {
  var params = {'date': date.toIso8601String()};
  Uri uri = Uri.parse('URL');
  final newURI = uri.replace(queryParameters: params);
  http.Response response = await http.get(
    newURI,
    headers: {"Accept": "application/json"},
  );

  List foo = json.decode(response.body);
  return foo;
}
like image 754
sebastian rincon Avatar asked Sep 04 '25 16:09

sebastian rincon


1 Answers

You can't iterate directly on future but you can wait for the future to complete and then iterate on the List.

You can use either of these methods, depending upon your use-case.

List dailyTaskList = await getDailyTask(DateTime.now());
// Now you can iterate on this list.
for (var task in dailyTaskList) {
  // do something
}

or

getDailyTask(DateTime.now()).then((dailyTaskList) {
  for (var task in dailyTaskList) {
    // do something
  }
});
like image 164
Zeeshan Hussain Avatar answered Sep 07 '25 13:09

Zeeshan Hussain