sanitizeName function

String sanitizeName(
  1. String name, {
  2. Set<String> extraKeywords = const <String>{},
})

Transforms a Python identifier into the closest possible legal Dart identifier by prepending a $ character. Dart keywords and built-in types are respected. As an example, a Python function called get will be turned into $get in Dart.

Implementation

String sanitizeName(
  String name, {
  Set<String> extraKeywords = const <String>{},
}) {
  /// Reference: https://dart.dev/language/keywords
  const Set<String> dartKeywords = <String>{
    "abstract",
    "as",
    "assert",
    "async",
    "await",
    "base",
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "covariant",
    "default",
    "deferred",
    "do",
    "dynamic",
    "else",
    "enum",
    "export",
    "extends",
    "extension",
    "external",
    "factory",
    "false",
    "final",
    "finally",
    "for",
    "Function",
    "get",
    "hide",
    "if",
    "implements",
    "import",
    "in",
    "interface",
    "is",
    "late",
    "library",
    "mixin",
    "new",
    "null",
    "on",
    "operator",
    "part",
    "required",
    "rethrow",
    "return",
    "sealed",
    "set",
    "show",
    "static",
    "super",
    "switch",
    "sync",
    "this",
    "throw",
    "true",
    "try",
    "typedef",
    "var",
    "void",
    "when",
    "while",
    "with",
    "yield",
  };

  /// Reference: https://dart.dev/language/built-in-types
  const Set<String> dartBuiltInTypes = <String>{
    "int",
    "double",
    "num",
    "String",
    "bool",
    "List",
    "Map",
    "Set",
    "Runes",
    "Symbol",
    "DateTime",
    "Duration",
    "Object",
    "Null",
    "Enum",
    "Future",
    "Stream",
    "Iterable",
    "Iterator",
    "Never",
  };
  if (dartKeywords.contains(name) ||
      dartBuiltInTypes.contains(name) ||
      extraKeywords.contains(name)) {
    return "\$$name";
  }
  return name;
}