toSnakeCase static method
Converts raw into a Dart-friendly snake_case identifier.
Non-alphanumeric separators are collapsed to underscores, camel-case boundaries are split, and the final value is lowercased.
Throws a FormatException when the normalized value is empty or starts with a number.
Implementation
static String toSnakeCase(String raw) {
final normalized = raw
.trim()
.replaceAllMapped(
RegExp(r'([a-z0-9])([A-Z])'),
(match) => '${match[1]}_${match[2]}',
)
.replaceAll(RegExp(r'[^A-Za-z0-9]+'), '_')
.replaceAll(RegExp(r'_+'), '_')
.replaceAll(RegExp(r'^_|_$'), '')
.toLowerCase();
if (normalized.isEmpty) {
throw const FormatException('Name must not be empty.');
}
if (RegExp(r'^[0-9]').hasMatch(normalized)) {
throw const FormatException('Name must not start with a number.');
}
return normalized;
}