DEV Community

rrtutors
rrtutors

Posted on • Originally published at rrtutors.com

Flutter list all files in directory

How to create a folder in flutter application and List all files in directory. In this example we will read all folders list from external directory and show the all folders and files. We can also create folder in the external directory. To create a folder we will use path_provider plugin and await getApplicationDocumentsDirectory() method

flutter how to create folder
To create a folder in internal storage we will use the below code

Future<String> createFolderInAppDocDir(String folderName) async {
  //Get this App Document Directory

  final Directory _appDocDir = await getApplicationDocumentsDirectory();
  //App Document Directory + folder name
  final Directory _appDocDirFolder =
  Directory('${_appDocDir.path}/$folderName/');

  if (await _appDocDirFolder.exists()) {
    //if folder already exists return path
    return _appDocDirFolder.path;
  } else {
    //if folder not exists create folder and then return its path
    final Directory _appDocDirNewFolder =
    await _appDocDirFolder.create(recursive: true);
    return _appDocDirNewFolder.path;
  }
}

Enter fullscreen mode Exit fullscreen mode

To List all files in directory from internal storage first we will fetch all the files and folder by using below code and then pass this data to GridView.builder() to show the files.

List<FileSystemEntity> _folders;
Future<void> getDir() async {
  final directory = await getApplicationDocumentsDirectory();
  final dir = directory.path;
  String pdfDirectory = '$dir/';
  final myDir = new Directory(pdfDirectory);
  setState(() {
    _folders = myDir.listSync(recursive: true, followLinks: false);
  });
  print(_folders);
}
Enter fullscreen mode Exit fullscreen mode

Delete a file from internal storage in flutter application

To delete file/folder we will use the below code.

await _folders[index].delete()
Enter fullscreen mode Exit fullscreen mode

.

To download complete code flutter create directory examples

Discussion (0)