isValidDartIdentifier static method

bool isValidDartIdentifier(
  1. String identifier
)

Validates if a string is a valid Dart identifier.

Checks if the string follows Dart identifier rules:

  • Starts with letter or underscore
  • Contains only letters, digits, and underscores
  • Is not a reserved word

Parameters:

  • identifier: The string to validate

Returns true if the identifier is valid.

Implementation

static bool isValidDartIdentifier(String identifier) {
  if (identifier.isEmpty) return false;

  // Check format
  if (!RegExp(r'^[a-zA-Z_][a-zA-Z0-9_]*$').hasMatch(identifier)) {
    return false;
  }

  // Check for reserved words (basic check)
  const reservedWords = {
    'abstract',
    'as',
    'assert',
    'async',
    'await',
    'break',
    'case',
    'catch',
    'class',
    'const',
    'continue',
    'default',
    'do',
    'else',
    'enum',
    'export',
    'extends',
    'false',
    'final',
    'finally',
    'for',
    'if',
    'import',
    'in',
    'is',
    'library',
    'new',
    'null',
    'operator',
    'part',
    'return',
    'static',
    'super',
    'switch',
    'this',
    'throw',
    'true',
    'try',
    'var',
    'void',
    'while',
    'with',
  };

  return !reservedWords.contains(identifier.toLowerCase());
}