findFiles method

List<File> findFiles(
  1. String directory, {
  2. String? extension,
  3. Pattern? namePattern,
  4. bool recursive = true,
})

Find files matching criteria in a directory

Implementation

List<File> findFiles(
  String directory, {
  String? extension,
  Pattern? namePattern,
  bool recursive = true,
}) {
  final dir = Directory(directory);
  if (!dir.existsSync()) {
    return [];
  }

  return dir.listSync(recursive: recursive).whereType<File>().where((file) {
    final fileName = file.path.split(Platform.pathSeparator).last;

    if (extension != null && !fileName.endsWith(extension)) {
      return false;
    }

    if (namePattern != null && !namePattern.allMatches(fileName).isNotEmpty) {
      return false;
    }

    return true;
  }).toList();
}