A string is used to hold a sequence of characters – letters, numbers, and special characters. In Dart language, strings are simply a sequence of UTF-16 (16-bit Unicode Transformation Format) code units. The Unicode format maps a unique numeric character to represent every digit, letter, or symbol. 

rune can be defined as an integer used to represent any Unicode code point. As a Dart string is a simple sequence of UTF-16 code units, 32-bit Unicode values in a string are represented using a special syntax. The String class in the dart: core library gives ways to access runes. For example – The theta (Θ) symbol is signified by using the corresponding Unicode equivalent \u0398; here ‘\u’ refers to Unicode, and the laughing emoji 😀 is represented as \u{1f600}. and the numbers are in hexadecimal. Sometimes the hex digits are more than 4 digits then they should be placed in curly brackets ({}).

void main() {

   var heart = '\u2665';
   var laugh = '\u{1f600}';
   print('heart is $heart');
   print('laugh is $laugh');
}

Output

heart is ♥
laugh is 😀

Runes can be accessed using the String class available in the dart: core library. The String code units/runes can be accessed in the following three ways –

  • Using String.codeUnitAt() function
  • Using String.codeUnits property
  • Using String.runes property

Using String.codeUnits property

The codeUnits property returns a list of UTF-16 code units for a specified string. This property returns an unchangeable list of the 16-bit UTF-16 code units of the given string. The syntax is given by String.codeUnits;

import 'dart:core';

void main() {
  String data = 'SagarKoju';
  print(data.codeUnits);
}

The output is given by

[83, 97, 103, 97, 114, 75, 111, 106, 117]

The codeUnits returned the list of the code unit corresponding to the given character.

Using String.codeUnitAt() function

It is used to return the UTF-16 code unit at the specified index of this string. The syntax is given below. String.codeUnitAt(int index);

import 'dart:core';
void main() {
  String name= 'SagarKoju';
  print(name.codeUnitAt(5));
}

The output is given by

75

In the above code, the variable name holds the string value “SagarKoju”. We called the codeuUnitAt() function and passed the index position. It returned the code unit of the 5th index character.

Using String. runes property

The runes property is used to iterate the given string through the UTF-16 code unit. The Syntax is given by String.runes;

import 'dart:core';

void main() {
  
String name = 'SagarKoju';
  name.runes.forEach((e) {
    var data = String.fromCharCode(e);
    print(data);
  });
  final string = String.fromCharCodes([68]);
  print(string);
}

The Output is given by

S
a
g
a
r
K
o
j
u
D

Thank you For Reading the Article about Runes in Dart