Dart Strings & Interpolation
A String is an immutable sequence of UTF-16 code units. Every string operation returns a new string; the original never changes.
String literals
void main() {
var single = 'It\'s single-quoted';
var dq = "It's double-quoted";
var raw = r'C:\new\table — no escapes in a raw string';
var multi = '''
Line one
Line two (indent kept)''';
print(single);
print(dq);
print(raw);
print(multi);
print('Tab:\tEnd\nNew line and a \u{1F3AF}');
}It's single-quoted
It's double-quoted
C:\new\table — no escapes in a raw string
Line one
Line two (indent kept)
Tab: End
New line and a 🎯
| Escape | Meaning |
|---|---|
\n, \t |
New line, tab |
\', \", \\ |
Quote, backslash |
\$ |
A literal dollar sign |
\u{1F600} |
Unicode code point |
Interpolation
Insert a value with $name, or any expression with ${...}. Interpolation calls toString() for you.
class Point {
final int x, y;
Point(this.x, this.y);
@override
String toString() => 'Point($x, $y)';
}
void main() {
var name = 'Linh';
var items = 3;
var price = 4.5;
var p = Point(2, 5);
print('Hi $name!');
print('$items items cost \${(items * price).toStringAsFixed(2)}');
print('Name has ${name.length} letters, upper: ${name.toUpperCase()}');
print('Location: $p');
print('${items > 2 ? 'many' : 'few'} items');
}Hi Linh!
3 items cost $13.50
Name has 4 letters, upper: LINH
Location: Point(2, 5)
many items
Tip: Write
$name, not${name}, when interpolating a plain identifier — the linter flags unnecessary braces. Use braces only for expressions like${a + b}or${user.name}.
Common methods
void main() {
var s = ' Dart is fun ';
var t = s.trim();
print('[$t]');
print(t.length);
print(t.toUpperCase());
print(t.contains('is'));
print(t.startsWith('Dart'));
print(t.indexOf('fun'));
print(t.substring(0, 4));
print(t.replaceAll(' ', '_'));
print(t.split(' '));
print(t[0]);
print('ab' * 3);
print('7'.padLeft(3, '0'));
print('Dart'.compareTo('Java'));
print(''.isEmpty);
}[Dart is fun]
11
DART IS FUN
true
true
8
Dart
Dart_is_fun
[Dart, is, fun]
D
ababab
007
-1
true
| Method | Purpose |
|---|---|
trim(), trimLeft(), trimRight() |
Remove whitespace |
split(pattern) |
Break into a List<String> |
substring(start, [end]) |
Slice (end exclusive) |
indexOf, lastIndexOf |
Find position, or -1 |
replaceFirst, replaceAll |
Replace text (also accept a RegExp) |
padLeft, padRight |
Fixed-width formatting |
isEmpty, isNotEmpty |
Length checks |
Building strings efficiently
Concatenating with + in a loop creates many temporary strings. Use a StringBuffer, or join a list:
void main() {
final buffer = StringBuffer();
for (var row = 1; row <= 3; row++) {
buffer.write('Row $row: ');
buffer.writeAll(List.filled(row, '*'));
buffer.writeln();
}
print(buffer.toString().trimRight());
final words = ['red', 'green', 'blue'];
print(words.join(', '));
}Row 1: *
Row 2: **
Row 3: ***
red, green, blue
Strings and Unicode
length counts UTF-16 code units, not visible characters. Emoji outside the Basic Multilingual Plane take two units. Use runes for code points:
void main() {
var word = 'Phở';
var emoji = '🎯';
print(word.length);
print(emoji.length);
print(emoji.runes.length);
print(word.codeUnitAt(0));
print(String.fromCharCode(68));
print(word.split('').reversed.join());
}3
2
1
80
D
ởhP
Note: For user-perceived characters (grapheme clusters, such as flags or emoji with skin tones), use the
characterspackage from pub.dev.
Comparing strings
== compares contents, not identity. There's no separate equals method:
'dart' == 'Dart'.toLowerCase(); // trueTest yourself
Which line prints Total: 5 when a = 2 and b = 3?
- print('Total: $a + $b');
- print('Total: ${a + b}');
- print('Total: ' + a + b);
- print('Total: $(a + b)');
What is a raw string, written r'...'?
- A string with no escape processing
- A byte array
- A multi-line string
- A string that can be modified
What is the most efficient way to build a long string in a loop?
- Repeated
+ StringBufferString.concat- Interpolating the string into itself