List files and folders in a directory — Flutter

Ermias Kelbessa
2 min readMar 29, 2022
Photo by Beatriz Pérez Moya on Unsplash

In flutter to list files in a directory we can use two methods. list() and listSync() . Both methods belong to the Directory class from dart:io built-in package. So we have to import dart:io to access the Directory class, which is a reference to a directory (or folder ) on the file system. As an example lets list contents of C drive on windows (C:/).

import 'dart:io';List<FileSystemEntity> files = [];void listFilesAndDirs() {    final dir = Directory("C:/");files = dir.listSync();print(files);
}

Next, just call this function in the main function and you can see the result on the terminal or debug console if you are running it on vscode.

void main() {    listFilesAndDirs();    runApp(MyApp());}

And the output of this code might look something like:

[Directory: 'C:/$Recycle.Bin', Directory: 'C:/$WINDOWS.~BT', Directory: 'C:/$WinREAgent', File: 'C:/hiberfil.sys', Directory: 'C:/Intel', Directory: 'C:/OneDriveTemp', File: 'C:/pagefile.sys', Directory: 'C:/PerfLogs', Directory: 'C:/Program Files', Directory: 'C:/Program Files (x86)', Directory: 'C:/ProgramData', Directory: 'C:/Programs', Directory: 'C:/Recovery', File: 'C:/swapfile.sys', Directory: 'C:/Users', Directory: 'C:/Windows', Directory: 'C:/Windows.old']

What about sub-folders

Simply by passing recursive: true as an argument directories are recursed into.

You need you need to run your flutter project as an administrator if you are scanning multiple folders since some may require it.

import 'dart:io';List<FileSystemEntity> files = [];void listFilesAndDirs() {    final dir = Directory("C:/");    files = dir.listSync(recursive: true,);    print(files);}

This one will output.

JK it's too large. 

If you are developing for android device path name is different. Other stuff can stay the same. For example common path for internal storage root directory is ‘/storage/emulated/0’ on android.

final dir = Directory('/storage/emulated/0');

As you can see this is a simple example about file systems utilizing only built-in package. If you want a deep dive into file system on flutter, check out packages like path_provider, path_provider_ex, file_manager.

--

--