I am using Dart and Flutter.
I am getting the message: Future<List>’ used in the ‘for’ loop must implement ‘Iterable’.
First, I need to get a list of files using async/await.
This function has return type: Future<List<FileSystemEntity>>
In the getFolderFiles() function, I need to loop through the files list.
I need to have both functions.
Could you please advise how to access Future<List<FileSystemEntity>>
from the getFolderFiles() function.
Thank You
The code:
List<String> myfiles = [];
Future<List<FileSystemEntity>> getFilesList() async {
Directory dir = Directory('C:/test');
final List<FileSystemEntity> entities = await dir.list().toList();
return entities;
}
List<String> getFolderFiles() {
for(var file in getFilesList()) {
myfiles.add(file.path.split('/').last);
}
return myfiles;
}
2
Answers
You can’t iterate over a
Future
. You’ll need to either useawait
orthen
to get the actual value.An example of the former (I’ve marked where I made changes):
Note that this now returns a
Future
too, as you can’t magically turn an asynchronous operation into a synchronous one. So any code callinggetFolderFiles
will also have to useawait
orthen
.If working with asynchronous operations is new for you, I recommend checking out:
Frank solved your problem. However, to simplify your code and take advantage of streams, you could rewrite your first function as follows: