getUniqueFileName static method

String getUniqueFileName(
  1. String fileName
)

Implementation

static String getUniqueFileName(String fileName) {
  if (!File(localStoragePath + fileName).existsSync()) {
    // File does not exist, no need to add a suffix
    return localStoragePath + fileName;
  }
  // Get the file name and extension
  String baseName = fileName.split('.').first;
  String fileExtension = fileName.split('.').length > 1 ? '.${fileName.split('.').last}' : '';

  // Check for existing files with the same base name
  int suffix = 1;
  String uniqueFileName;

  do {
    uniqueFileName = '$baseName ($suffix)$fileExtension';
    suffix++;
  } while (File(localStoragePath + uniqueFileName).existsSync());

  return localStoragePath + uniqueFileName;
}