---
title: "Escaping Characters and Unicode in Dart String Literals"
date: "2026-12-03T09:56:00+07:00"
description: "Escape sequences, raw strings, runes, and the grapheme-cluster trap: a practical guide to Unicode-correct Dart strings for emoji, flags, and paths."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-string-escapes-unicode.jpg"
alt: "A Dart string literal split apart into UTF-16 code units, Unicode code points, and an emoji flag grapheme cluster"
tags: ['dart', 'dart-language', 'unicode', 'strings', 'emoji']
---

Every Dart string is a sequence of UTF-16 code units, which is a perfectly fine mental model right up until a user pastes an emoji flag into a text field. Escapes, runes, and grapheme clusters are three different layers describing the same text, and most string bugs come from quietly mixing them up.

## Escape sequences you get for free

A string literal wrapped in single or double quotes interprets backslash escapes. The full set you will actually use looks like this:

| Sequence | Produces |
|---|---|
| `\n` | Line feed (newline) |
| `\t` | Horizontal tab |
| `\\` | A single backslash |
| `\'` and `\"` | A quote of that kind |
| `\$` | A literal dollar sign |
| `\uXXXX` | Code point with exactly four hex digits |
| `\u{XXXXX}` | Code point with one to six hex digits |
| `\b`, `\r`, `\f`, `\v` | Backspace, carriage return, form feed, vertical tab |

Two characters deserve special attention. `$` starts string interpolation, so a literal dollar sign must be escaped as `\$`, and a backslash must always be doubled because a lone `\` signals the start of an escape sequence:

```dart
void main() {
  final report = 'First line\nSecond line\ttabbed';
  final windowsPath = 'C:\\Users\\ada\\notes.txt';
  final price = 'Total: \$9.99';
  final quote = 'It\'s easier to escape than to switch "quotes"';
  print(report);
  print(windowsPath);
  print(price);
  print(quote);
}
```

Notice that the quote example only escapes the single quote, because the string is delimited by single quotes and the double quotes inside need no treatment at all. Choosing the delimiter that matches the text is usually cleaner than piling up backslashes.

## Raw strings: turning escapes off

Prefixing a literal with `r` makes every backslash literal. Raw strings disable all escapes *and* interpolation, so they are the right tool when the content is dominated by backslashes:

```dart
void main() {
  final windowsPath = r'C:\Users\ada\notes.txt';
  final digitPattern = r'^\d{3}-\d{4}$';
  final message = r'Use $HOME to expand the home directory';
  print(windowsPath);
  print(digitPattern);
  print(message);
}
```

The trade-off is symmetric: a raw string cannot express `\n`, `\u2665`, or `$name`. When both a literal backslash and interpolation belong in the same value, escape selectively instead: `'C:\\logs\\$day.txt'` yields `C:\logs\2026-12-03.txt`. The rule of thumb is simple — if backslashes dominate the text, go raw; if interpolation dominates with an occasional backslash, escape by hand.

## Unicode escapes and the runes getter

The usual way to write a Unicode code point is `\uXXXX` with four hex digits, which covers everything in the Basic Multilingual Plane, such as the heart character `\u2665`. Anything beyond four digits needs curly braces: the laughing emoji is `\u{1f606}`, and the Danish flag is written as a pair of code points, `\u{1F1E9}\u{1F1F0}`.

To read those code points back out of a string, use the `runes` getter:

```dart
void main() {
  const heart = '\u2665';
  const laughing = '\u{1f606}';
  const danishFlag = '\u{1F1E9}\u{1F1F0}';
  print(heart); // ♥
  print(laughing); // 😆
  print(danishFlag); // 🇩🇰
  print('flag code points: ${danishFlag.runes.length}'); // 2
}
```

`runes` exposes Unicode code points, which is exactly what you want when serializing, hashing, or inspecting text. It is still not what a user would call "one character", and that distinction is where the real trouble starts.

## Three layers of "character"

Because a Dart string is stored as UTF-16 code units, three abstractions sit on top of the same bytes. Using the string `Hi 🇩🇰` as a reference:

| Abstraction | Dart API | What one step means | Steps in `Hi 🇩🇰` |
|---|---|---|---|
| Code units (UTF-16) | `length`, `[]`, `substring` | One 16-bit unit | 7 |
| Code points | `runes` | One Unicode scalar value | 5 |
| Grapheme clusters | `.characters` | One user-perceived character | 4 |

The flag emoji alone accounts for four code units and two code points, yet a human reads it as a single character. Any operation expressed in code units can therefore cut through the middle of a glyph.

## The substring trap with emoji flags

The official documentation demonstrates the hazard directly: taking the "last character" of `Hi 🇩🇰` with `substring` returns half of a surrogate pair, which prints as replacement garbage, while `characters.last` returns the flag itself:

```dart
import 'package:characters/characters.dart';

void main() {
  const hi = 'Hi \u{1F1E9}\u{1F1F0}';
  print('code units: ${hi.length}'); // 7
  print('code points: ${hi.runes.length}'); // 5
  print('grapheme clusters: ${hi.characters.length}'); // 4
  print('broken tail: ${hi.substring(hi.length - 1)}');
  print('last character: ${hi.characters.last}');
}
```

The `characters` extension comes from the `characters` package. Flutter depends on it already; for a pure Dart package, add `characters: ^1.4.1` to your `pubspec.yaml`. The package treats a string as a sequence of Unicode extended grapheme clusters, which are the boundaries defined by the Unicode text segmentation standard.

## Equality compares code units

String `==` tests whether two strings contain the same sequence of code units. That has a consequence people discover the hard way: visually identical text is not always equal, because Unicode lets the same glyph be encoded in more than one way:

```dart
void main() {
  const precomposed = 'é'; // single code point
  const decomposed = 'e\u0301'; // e + combining acute accent
  print(precomposed == decomposed); // false
  print(precomposed.runes.length); // 1
  print(decomposed.runes.length); // 2
  print('♥' == '\u2665'); // true — identical code units
}
```

The reverse case is reassuring: two different source spellings of the same escape produce equal strings, because equality sees the resulting code units rather than how you typed them. If your data comes from users or external APIs, decide explicitly whether normalization matters for your comparisons; Dart's `==` will never normalize for you.

## A safe truncation helper

Once you accept that code units are not characters, truncation becomes a one-line fix: check `text.characters.length <= maxCharacters`, and when the text is longer, return `'${text.characters.take(maxCharacters)}…'` instead of slicing with `substring`. Counting with `characters.length` and slicing with `characters.take()` keeps combined characters and emoji sequences intact — truncating `A 🇬🇧 text in English` to 15 characters yields `A 🇬🇧 text in Eng…` rather than half a flag, which is exactly what the `characters` package documentation recommends whenever you manipulate text at the character level.

## Takeaways

- A Dart string is a sequence of UTF-16 code units; `runes` gives you code points, and `characters` gives you user-perceived characters.
- Escape `\n`, `\t`, `\\`, `\'`, `\"`, `\$` in normal strings, or switch to a raw string with `r` when backslashes dominate.
- Use `\uXXXX` for BMP characters and `\u{XXXXX}` for emoji and anything outside the BMP.
- `substring` and `length` operate on code units, so they can split emoji flags and combining marks in half.
- String `==` compares code units only, with no normalization applied.

**Takeaway:** Treat a Dart string as UTF-16 code units by default, reach for escapes or raw strings only for literal syntax, `runes` when you need code points, and the `characters` package whenever the question is "how many characters does a human see?".

## References

- https://dart.dev/language/built-in-types
- https://pub.dev/packages/characters
- https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
- https://api.dart.dev/dart-core/Runes-class.html
