Dart String Interpolation
Dart String Interpolation
String interpolation means putting a value inside a string.
To do this, write a dollar sign $ followed by the variable name, inside the string:
Result:
Hello, Emma!
Dart replaces $name with the value of the variable.
You can use as many variables as you want in one string:
Example
void main() {
var name = 'Emma';
var city = 'Oslo';
var age = 28;
print('$name lives in $city and is $age years old.');
}
Try it Yourself »
Result:
Emma lives in Oslo and is 28 years old.
Expressions With ${}
An expression is a piece of code that gives a value, like a + b.
To put an expression inside a string, write it inside ${}:
Example
void main() {
var price = 20;
var quantity = 3;
print('Total: ${price * quantity} dollars');
}
Try it Yourself »
Result:
Total: 60 dollars
You also need ${} when you use a property or a method of a variable:
Example
void main() {
var name = 'Emma';
print('${name.toUpperCase()} has ${name.length} letters');
}
Try it Yourself »
Result:
EMMA has 4 letters
If you forget the curly brackets, Dart only uses the variable name and prints the rest as normal text:
Example
void main() {
var name = 'Emma';
print('Letters: $name.length');
print('Letters: ${name.length}');
}
Try it Yourself »
Result:
Letters: Emma.length
Letters: 4
Interpolation vs Concatenation
You can only join a string with another string when you use +.
If you try to add a number to a string, the program does not run:
Result:
main.dart:3:19: Error: A value of type 'int' can't be assigned to a variable of type 'String'.
print('Age: ' + age);
^
With interpolation, Dart turns the value into text for you:
Example
void main() {
var age = 28;
var height = 1.68;
var isStudent = true;
print('Age: $age');
print('Height: $height');
print('Student: $isStudent');
}
Try it Yourself »
Result:
Age: 28
Height: 1.68
Student: true
Tip: Interpolation is the normal way to build strings in Dart.
It is shorter than + and works with any type of value.
Print a Dollar Sign
To print a real dollar sign, put a backslash before it: \$.
You can also use a raw string, which does no interpolation at all:
Example
void main() {
var price = 15;
print('Price: \$$price');
print(r'Price: $price');
}
Try it Yourself »
Result:
Price: $15
Price: $price
Multi-line Strings
Interpolation also works in multi-line strings:
Example
void main() {
var item = 'Coffee';
var price = 3.5;
var count = 2;
print('''Receipt
Item: $item
Count: $count
Total: ${price * count}''');
}
Try it Yourself »
Result:
Receipt
Item: Coffee
Count: 2
Total: 7.0