escape method

String escape({
  1. QuoteType quotes = QuoteType.single,
  2. bool ascii = true,
})

Escapes a String such that it can be used as a string literal in generated code.

quotes specifies the type of surrounding quotes to add. Existing occurrences of the specified quote character will be escaped.

If ascii is true, all non-ASCII code-points will be escaped as a Unicode literal sequence (\u{XXXXXX}).

Calling jsonEncode on a String is similar, but escape has some notable differences:

  • jsonEncode always uses surrounding double-quotes.
  • jsonEncode does not escape $, which is used in Dart string literals for string interpolation.
  • jsonEncode usually does not escape non-ASCII characters.
  • jsonEncode escapes a vertical tab (\v') as \u000b`.
  • If there is no canonical escape sequence for a character that needs to be escaped (such as (\n, \t, etc.), jsonEncode encodes the character as \uXXXX (which represents a UTF-16 code unit) whereas escape uses \u{XXXXXX} (which represents a Unicode code point).

In summary, comparing jsonEncode to escape (when called with default arguments):

Input jsonEncode escape
'$' r"$" r'$'
'\v' r"\u000b" r'\v'
'\u0000' r"\u0000" r'\u{0}'
'\u2665' r"♥" r'\u{2665}'
'\u{1f600}' r"😀" r'\u{1f600}'

Implementation

String escape({
  QuoteType quotes = QuoteType.single,
  bool ascii = true,
}) =>
    String.fromCharCodes(
      runes.escape(quotes: quotes, ascii: ascii),
    );