escapeDartString function
Returns a quoted String literal for value
that can be used in generated
Dart code.
Implementation
String escapeDartString(String value) {
var hasSingleQuote = false;
var hasDoubleQuote = false;
var hasDollar = false;
var canBeRaw = true;
value = value.replaceAllMapped(_escapeRegExp, (match) {
final value = match[0]!;
if (value == "'") {
hasSingleQuote = true;
return value;
} else if (value == '"') {
hasDoubleQuote = true;
return value;
} else if (value == r'$') {
hasDollar = true;
return value;
}
canBeRaw = false;
return _escapeMap[value] ?? _getHexLiteral(value);
});
if (!hasDollar) {
if (hasSingleQuote) {
if (!hasDoubleQuote) {
return '"$value"';
}
// something
} else {
// trivial!
return "'$value'";
}
}
if (hasDollar && canBeRaw) {
if (hasSingleQuote) {
if (!hasDoubleQuote) {
// quote it with single quotes!
return 'r"$value"';
}
} else {
// quote it with single quotes!
return "r'$value'";
}
}
// The only safe way to wrap the content is to escape all of the
// problematic characters - `$`, `'`, and `"`
final string = value.replaceAll(_dollarQuoteRegexp, r'\');
return "'$string'";
}