CodeBlanks Logo Icon CodeBlanks

String interpolation

Learn to embed values in strings with \$ and \${}.

String interpolation

In Dart you use interpolation to embed a variable or expression inside a string. For a simple variable the $ prefix is enough: "Welcome $name". For an expression (method call, operation) you need curly braces: "Length: ${name.length}".

Interpolation is more readable than concatenating strings with +. Writing "Welcome $name" instead of "Welcome " + name is the Dart way. Any valid Dart expression can be embedded.

$ vs ${}

$ embeds only a variable name: "$name". If you want a method call or operation you must use ${}: "${name.toUpperCase()}". Without braces, $name.toUpperCase() makes Dart embed only $name and treat the rest as plain text.

Rule: $ for a simple variable, ${} for an expression. When unsure, ${} always works.

Practice Print with interpolation

Declare a String variable name with the value "Alex". Then print it to the screen with print("Welcome $name");. The output on a single line must be Welcome Alex.

Starter code

main.dart
// Declare name and print with interpolation

Sample solution

main.dart
String name = "Alex";
print("Welcome $name");

Expected output

Welcome Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the output of this code?

main.dart
String name = "Alex";
print("Welcome $name");
  • Welcome name
  • Welcome Alex Correct answer
  • Welcome $name
  • Welcome ${name}

Explanation: $name is replaced by the value of name; the output is Welcome Alex.

2 Complete the interpolation

Question
String name = "Alex";
print("Welcome ____");
Answer
String name = "Alex";
print("Welcome $name");

Explanation: $name embeds the variable value into the string.

3 Match the expression to the form

Term Meaning
$name Simple variable
${name.length} Expression (method/property)
${a + b} Arithmetic expression
Welcome $name Variable embedding

All lessons in Beginner