toSafeFileName static method

String toSafeFileName(
  1. String filename, {
  2. String separator = '-',
  3. bool withSpaces = false,
  4. bool lowercase = false,
  5. bool onlyAlphanumeric = false,
})

makes a filename safe

Implementation

static String toSafeFileName( String filename, {String separator = '-', bool withSpaces = false, bool lowercase = false, bool onlyAlphanumeric = false})
{
  final List<String> reservedCharacters = ['?', ':', '"', '*', '|', '/', '\\', '<', '>', '+', '[', ']'];
  final RegExp onlyAlphanumericRegex = RegExp(r'''[^a-zA-Z0-9\s.]''');
  String returnString = filename;
  onlyAlphanumeric ? returnString = returnString.replaceAll(onlyAlphanumericRegex, '') : reservedCharacters.forEach((c) => returnString = returnString.replaceAll(c, separator));
  if (!withSpaces) returnString = returnString.replaceAll(' ', separator);
  return lowercase ? returnString.toLowerCase() : returnString;
}