In this tutorial you will learn about the Dart Runes and its application with practical example.
Dart Runes
String is used to hold sequence of characters – letters, numbers, and special characters. In Dart, string is represented as sequence of Unicode UTF-16 characters. If you want to use 32-bit Unicode characters within a string then it must be represented using a special syntax. A rune is an integer representing a Unicode code point. For example, the heart character ‘♥ is represented using corresponding unicode equivalent \u2665, here \u stands for unicode and the numbers are hexadecimal, which is essentially an integer. If the hex digits are more or less than 4 digits, place the hex value in curly brackets ({ }). For example, the laughing emoji ‘😆’ is represented as \u{1f600}.
Example:-
1 2 3 4 5 6 7 |
void main() { var heart = '\u2665'; var laugh = '\u{1f600}'; print(heart); print(laugh); } |
Output:-
1 2 |
♥ 😀 |
Runes can be accessed using the String class available in dart:core library. The String code units / runes can be accessed in following three ways –
- Using String.codeUnitAt() function
- Using String.codeUnits property
- Using String.runes property
String.codeUnitAt() Function
The Code units of a character in a string can be accessed through their indexes. The codeUnitAt() function returns the 16-bit UTF-16 code unit at the given index.
Syntax:-
1 |
String.codeUnitAt(int index); |
Example:-
1 2 3 4 5 |
void main(){ String str = 'W3Adda'; print("W3Adda - String codeUnitAt Function"); print(str.codeUnitAt(0)); } |
Output:-
String.codeUnits Property
The codeUnits property returns a list of UTF-16 code units for specified string.
Syntax:-
1 |
String.codeUnits; |
Example:-
1 2 3 4 5 |
void main(){ String str = 'W3Adda'; print("W3Adda - String codeUnits Property"); print(str.codeUnits); } |
Output:-
String.runes Property
This runes property iterate through the UTF-16 code units in a given string.
Syntax:-
1 |
String.runes |
Example:-
1 2 3 4 5 6 7 8 |
void main(){ String str = 'W3Adda'; print("W3Adda - String runes Property Example."); str.runes.forEach((int rune) { var chr=new String.fromCharCode(rune); print(chr); }); } |
Output:-