String interpolation
- Dart course
- Beginner
- Lesson 5/116
- 4 min
Learn to embed variables in strings with \$.
String interpolation
With string interpolation you can embed variables or expressions inside a string. This uses the $ sign.
For a simple variable, just write $name. For an expression or property you need curly braces: ${name.length} or ${a + b}.
This is more readable than concatenating with +. Instead of 'Hello ' + name you write 'Hello $name'.
Practice Greet by name
Declare a name variable (set to Alex) and use string interpolation to print Hello Alex. That is, write it as 'Hello $name'.
Starter code
// Add the name variable and printSample solution
void main() {
var name = 'Alex';
print('Hello $name');
}Expected output
Hello Alex
When to use curly braces?
If the text following the $ sign is just an identifier (variable name), no curly braces are needed: $name, $age.
But if you use a property with a dot (name.length), an index (list[0]) or arithmetic (a + b), you must write ${...}.
If unsure, you can always use ${}; ${name} is also valid. What matters is being consistent.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Interpolation sign
var name = 'Derya'; print('Hello ____name');
var name = 'Derya'; print('Hello $name');
Explanation: The $ sign embeds the variable into the string.
2 Correct way to embed name.length in a string?
print('${name.length}');- $name.length
- $name(length)
- $[name.length]
- ${name.length} Correct answer
Explanation: Property access requires ${}.
3 Interpolation concepts
| Term | Meaning |
|---|---|
$name |
Simple variable |
${a + b} |
Expression embedding |
${name.length} |
Property access |
'Merhaba' |
Literal string |