Sub topic 3
Strings and interpolation
This chapter assumes you know how var, final, and const work, and that you have used strings in another language. It covers how Dart stores strings, how literals and interpolation work, the operations you will use most, and the mistakes that cause bugs.
The working model
A Dart String is an immutable sequence of UTF-16 code units. Two consequences follow:
- You cannot change a string in place. Every operation such as
trim()orreplaceAll()returns a new string. lengthcounts UTF-16 code units, not the characters a reader sees. This matters for emoji and accented text, covered below.
Dart has no separate char type. Indexing with s[0] returns a one-character String. The == operator compares contents, so 'ab' == 'a' + 'b' is true.
String literals
Dart offers several literal forms. Single and double quotes are equivalent, and the usual style is single quotes unless the text contains an apostrophe.
void main() {
final a = 'single quotes';
final b = "it's easy to include an apostrophe";
final c = 'or escape it: it\'s fine';
final raw = r'C:\temp\new $name';
final multi = '''
line one
line two''';
final joined = 'abc'
'def';
const emoji = '\u{1F600}';
print(a);
print(b);
print(c);
print(raw);
print(multi);
print(joined);
print(emoji);
}- A raw string, prefixed with
r, ignores escapes and interpolation. It is useful for Windows paths and regular expressions. - A triple-quoted string can span lines. A line break right after the opening quotes is ignored.
- Adjacent literals are joined at compile time, so
'abc' 'def'is'abcdef'. This is a clean way to split a long message across lines. - Common escapes are
\n,\t,\\,\$,\u00E9, and\u{1F600}.
Interpolation
Interpolation inserts the value of an expression into a string. There are two forms:
$nameinserts a single identifier.${expression}inserts any expression.
void main() {
final name = 'Ada';
final items = ['a', 'b'];
print('Hello, $name');
print('Length: ${name.length}');
print('Wrong: $items.length');
print('Right: ${items.length}');
print('Sum: ${1 + 2}');
print('Cost: \$5');
}This prints:
Hello, Ada
Length: 3
Wrong: [a, b].length
Right: 2
Sum: 3
Cost: $5What happens at runtime
Dart evaluates each interpolated expression and calls toString() on the result. It then concatenates the pieces in order.
Because interpolation uses toString(), you control how your own types appear in strings by overriding it:
class Temperature {
final double degrees;
const Temperature(this.degrees);
@override
String toString() => '${degrees.toStringAsFixed(1)}°C';
}
void main() {
print('Now: ${Temperature(21.456)}');
}This prints Now: 21.5°C. Without the override, you would see Instance of 'Temperature'.
Nested quotes and braces
Inside ${...} you can use any expression, including string literals with the same quote character:
void main() {
String? nickname;
print('Nick: $nickname');
print('Nick: ${nickname ?? 'none'}');
}The first line prints Nick: null. A null value does not throw. It is converted to the text null, which is a common source of strange output in a user interface. Handle null explicitly with ?? when the text is user-facing.
The Dart linter flags two style issues. unnecessary_brace_in_string_interps flags '${name}' where '$name' is enough. prefer_interpolation_to_compose_strings flags 'Hello, ' + name.
Common operations
Most string members are methods and getters on String. This example covers the ones you will use daily:
void main() {
const raw = ' Dart, Flutter ';
final s = raw.trim();
print(s.length);
print(s.toUpperCase());
print(s.split(', '));
print(s.substring(0, 4));
print(s.contains('Flu'));
print(s.startsWith('Da'));
print(s.indexOf('F'));
print(s.replaceAll('t', 'T'));
print('7'.padLeft(3, '0'));
print('ab' * 3);
print(s.isEmpty);
}The output is:
13
DART, FLUTTER
[Dart, Flutter]
Dart
true
true
6
DarT, FluTTer
007
ababab
falseA few details to keep in mind:
substring(start, end)has an exclusive end. An out-of-range index throws aRangeError.indexOfreturns-1when nothing matches.replaceAllaccepts aPattern, so you can pass aRegExp. UsereplaceAllMappedwhen the replacement depends on the match.- The
+operator requires aStringon both sides.'a' + 1is a compile-time error, so interpolate instead:'a${1}'. - Comparison with
<is not defined. UsecompareTo, which returns a negative number, zero, or a positive number.
Building large strings
Repeated + or interpolation inside a loop creates a new string each time. For many pieces, use a StringBuffer:
void main() {
final buffer = StringBuffer();
buffer.writeAll([1, 2, 3], ', ');
buffer.writeln();
for (var i = 1; i <= 2; i++) {
buffer.write('row $i;');
}
print(buffer.toString());
}The buffer collects pieces and creates the final string once when you call toString(). For a list of strings, list.join(', ') does the same job in one call.
Constant strings
A string literal is a compile-time constant when it has no interpolation, or when every interpolated value is itself a constant number, string, boolean, or null:
const greeting = 'Hello';
const message = '$greeting, world';Interpolating a final variable or a function call inside a const string is a compile-time error, because the value is only known at runtime. Use final for those strings instead.
Unicode: code units, runes, and characters
Because length counts UTF-16 code units, characters outside the Basic Multilingual Plane, such as most emoji, count as two:
void main() {
const smile = '\u{1F600}';
print(smile.length);
print(smile.codeUnits);
print(smile.runes.length);
print(smile.runes.first.toRadixString(16));
}This prints:
2
[55357, 56832]
1
1f600codeUnitsgives the raw UTF-16 values. The emoji is stored as a surrogate pair.runesgives Unicode code points, so the emoji is one rune.
A rune is still not always one visible character. The letter é can be stored as one code point or as e plus a combining accent, and a flag emoji is two code points. For user-visible characters, which Unicode calls grapheme clusters, use the characters package. Flutter already depends on it, and its string.characters getter splits text the way a reader would. Methods such as substring, split(''), and indexing work on code units and can cut an emoji in half. Avoid them for user-entered text such as names or messages.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Output shows `[a, b].length` | Used `$items.length` | Use `${items.length}` |
| Output shows `null` in the UI | Interpolated a nullable value | Use `${value ?? 'default'}` |
| Output shows `Instance of 'Foo'` | Class has no `toString()` override | Override `toString()` |
| `s[0] = 'x'` fails to compile | Strings are immutable | Build a new string |
| `RangeError` from `substring` | Index past `length` | Check `length` first |
| Emoji split into garbage | Used code-unit operations | Use the `characters` package |
| `const` string fails to compile | Interpolated a runtime value | Switch to `final` |
Exercise
What does this program print, and why? final list = [1, 2, 3]; print('Count: $list.length, first: ${list.first}');
Show answer
It prints Count: [1, 2, 3].length, first: 1. The short form $list interpolates only the identifier list, so .length stays as plain text. The ${list.first} form evaluates the expression and inserts 1. The fix is ${list.length}.
Exercise
The string '\u{1F600}' has length 2 but runes.length 1. Explain why, and name one case where relying on length would cause a bug in a text input field.
Show answer
length counts UTF-16 code units. The emoji's code point U+1F600 lies above U+FFFF, so UTF-16 stores it as a surrogate pair of two code units. runes iterates over Unicode code points, so it counts one. Relying on length would be wrong for a character limit, because one emoji would count as two characters. Slicing with substring could also cut the pair in half. Use the characters package to count and slice what the user sees.