Sub topic 3
Strings and interpolation
Prerequisites and the working model
This chapter assumes you can declare variables, call functions, and run a Dart program. A Dart string is a sequence of characters. String literals are usually written with single quotes or double quotes. Both forms have the same behavior.
Dart evaluates an interpolated string from left to right. A dollar sign introduces an expression:
$nameinserts the value of a simple identifier.${expression}inserts the result of a longer expression.\$writes a dollar sign without starting interpolation.\ninserts a newline.
Basic interpolation
Use interpolation instead of repeatedly joining strings with +. It keeps the relationship between text and values visible.
void main() {
final name = 'Dart';
var version = 3;
const pi = 3.14159;
version = version + 1;
print('Hello, $name $version');
print('Twice pi is ${pi * 2}');
print('A dollar sign costs \$5');
}The expression after ${ can contain operators, property access, function calls, and conditions. Use braces whenever Dart needs to know where the expression ends. For example, $name.length means “the value of name.length,” but ${name}Length means the value of name followed by the text Length.
A common mistake is trying to interpolate a statement. Interpolation accepts expressions that produce values, not declarations or control-flow statements.
Quotes and multiline text
Single-quoted and double-quoted strings can contain the other quote without escaping it. Escape a matching quote with a backslash.
Triple quotes create multiline strings. They are useful for templates, test data, and formatted messages.
void main() {
final title = 'Dart';
final message = '''
$title supports interpolation.
It also supports multiple lines.
''';
print(message);
}Raw strings disable escape processing. Prefix a string with r when backslashes should remain literal, such as in a regular expression or Windows path.
void main() {
const path = r'C:\projects\app\lib';
const pattern = r'\d+';
print(path);
print(pattern);
}Raw strings do not disable interpolation in every context you may expect, so use them mainly for backslash-heavy text. When literal dollar signs also matter, escape or construct the text carefully.
Useful string operations
Strings are immutable. An operation such as toUpperCase() returns a new string; it does not change the original value.
| Operation | Example | Result |
|---|---|---|
| Change case | `'dart'.toUpperCase()` | `DART` |
| Remove outer whitespace | `' Dart '.trim()` | `Dart` |
| Test a prefix | `'Dart'.startsWith('Da')` | `true` |
| Replace text | `'a-b'.replaceAll('-', '_')` | `a_b` |
Use StringBuffer when building a large string inside a loop. It avoids repeatedly creating intermediate strings.
Exercise
What does ${name}Length do when name contains the string "Dart"?
Show answer
It evaluates name, then appends the literal text "Length", producing "DartLength".