Carlos
Carlos

Reputation: 91

Emojis length error when Text() - flutter

I'm trying to show all of the emojis that I have on a JSON file (I stored their Unicode and their description). However, as Flutter cannot check that my keys (the unicode) have a length of 4 it shows an error. What can I do?

myEmoji = "\u{$key}";

ERROR: Error: An escape sequence starting with '\u' must be followed by 4 hexadecimal digits or from 1 to 6 digits between '{' and '}'.

EDIT: the key stored looks something like this : "1F601"

Upvotes: 0

Views: 784

Answers (3)

Quân
Quân

Reputation: 1

i used s.runes.length but still has wrong length of some emoji, use s.characters.length is more correct, i got this from the LengthLimitingTextInputFormatter code.

Upvotes: 0

Matthew Trent
Matthew Trent

Reputation: 3264

Perhaps this will help. Using the .runes method allows you to access the "true" length of a String that includes emojis.

void main() {
  String s = "heyπŸ‘€";
  print(s.runes.length); // prints 4
  print(s.length); // prints 5
}

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 89965

\u is used for a Unicode literal; it is parsed at compile-time. It cannot be used with a variable.

If you have a String with the hexadecimal representation of the Unicode code point, you will need to parse that String to an integer value and then use String.fromCharCode:

void main() {
  var codePointString = '1F601';
  var codePointValue = int.parse(codePointString, radix: 16);
  var emoji = String.fromCharCode(codePointValue);
  print(emoji); // Prints: 😁
}

Upvotes: 1

Related Questions