Skip to content
AgileLogics
5 min read

Strings

Prerequisites: Data types and type inference

A string is a piece of text in quotes. Single and double quotes work the same; single quotes are the common style.

String interpolation

Put $name inside a string to insert a variable, or ${ ... } for any expression:

void main() {
  final name = 'Ada';
  final age = 36;

  print('Hello, $name!');
  print('Next year you\'ll be ${age + 1}.');
  print('Your name has ${name.length} letters');
  print("It's easier with double quotes when the text has apostrophes.");
}
Hello, Ada!
Next year you'll be 37.
Your name has 3 letters
It's easier with double quotes when the text has apostrophes.
  • \' puts a single quote inside a single-quoted string.
  • Interpolation converts any value to text for you.

Joining strings

void main() {
  final first = 'Ada';
  print(first + ' Lovelace');
  print('Dart ' 'is ' 'fun');
}
Ada Lovelace
Dart is fun

String literals written next to each other are joined automatically — handy for breaking up long text. 'Age: ' + 36 is an error, though: + only joins strings. Use interpolation: 'Age: $age'.

Multi-line and raw strings

void main() {
  final name = 'Ada';
  final message = '''
Dear $name,
Thanks for signing up.''';
  print(message);
  print(r'C:\new\folder has no escapes, and $name stays as-is');
}
Dear Ada,
Thanks for signing up.
C:\new\folder has no escapes, and $name stays as-is
  • Triple quotes (''' or """) span several lines.
  • An r prefix makes a raw string: backslashes and $ are taken literally.

Common mistakes

  • Writing '$name.length' and expecting the length — Dart inserts name and prints .length as text. Use '${name.length}'.

Practice

Store a product name and a price, then print Coffee costs 3.5 EUR using interpolation.

Show solution
void main() {
  final product = 'Coffee';
  final price = 3.5;
  print('$product costs $price EUR');
}
Coffee costs 3.5 EUR