skip to Main Content

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


  1. You can’t iterate over a Future. You’ll need to either use await or then to get the actual value.


    An example of the former (I’ve marked where I made changes):

    // 👇                                   👇
    Future<List<String>> getFolderFiles() async {
      //              👇
      for(var file in await getFilesList()) {
          myfiles.add(file.path.split('/').last);
       }
      return myfiles;
    }
    

    Note that this now returns a Future too, as you can’t magically turn an asynchronous operation into a synchronous one. So any code calling getFolderFiles will also have to use await or then.


    If working with asynchronous operations is new for you, I recommend checking out:

    Login or Signup to reply.
  2. Frank solved your problem. However, to simplify your code and take advantage of streams, you could rewrite your first function as follows:

    Future<List<String>> getFolderFilesNew(List<String> files) async {
          await for (FileSystemEntity entity in Directory('C:/test').list()) {
            files.add(entity.path.split('/').last);
          }
         return files;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search