How can I write a 3 byte unicode character as string literal

14.3k Views Asked by At

Take for example the codes for these emoticons

For two-byte codes like Dingbats (2702 - 27B0)

'abcd\u2702efg'

works fine but for longer codes like \u1F601 this doesn't work.

String.fromCharCode(0x1f601)

works though.

main() {
  print('abcd\u2702efg');
  print('abcd\u1F601efg');
  print(new String.fromCharCode(0x1f601));
}

Try at DartPad

Is there a way to write U+1F601 as a string literal in Dart?

1

There are 1 best solutions below

0
On BEST ANSWER

Enclose the character code in curly braces:

print('abcd\u{1F601}efg');

From §16.5, "Strings", of the Dart Programming Language Specification, Second Edition:

Strings support escape sequences for special characters. The escapes are:

  • ...
  • \x HEX DIGIT1 HEX DIGIT2, equivalent to \u{HEX DIGIT1 HEX DIGIT2}.
  • \u HEX DIGIT1 HEX DIGIT2 HEX DIGIT3 HEX DIGIT4, equivalent to \u{HEX DIGIT1 HEX DIGIT2 HEX DIGIT3 HEX DIGIT4}.
  • \u{HEX DIGIT SEQUENCE} is the unicode scalar value represented by the HEX DIGIT SEQUENCE. It is a compile-time error if the value of the HEX DIGIT SEQUENCE is not a valid unicode scalar value.