On this page15 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. String Literals
  4. 2. Escape Characters and Raw Strings
  5. 3. Multi-Line Strings
  6. 4. String Interpolation
  7. 5. Joining Strings
  8. 6. Useful Properties and Methods
  9. 7. Strings Never Change
  10. 8. Strings and Numbers
  11. Code Examples
  12. Common Beginner Mistakes
  13. Practice Questions
  14. Practice Answers
  15. Key Takeaways

Lecture 009: Strings, Literals & Interpolation

Day4: Strings & Null Safety
Lecture009 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

Names, messages, addresses, passwords: almost every program works with text. In Dart, text is a String. This lecture shows how to write strings, put values inside them, and use the handful of string tools you will reach for every day.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 006–008: variables, data types, final and const.


Learning Objectives

  • Write string literals with single, double and triple quotes
  • Use escape characters and raw strings
  • Put values inside a string with interpolation ($name and ${...})
  • Join strings together
  • Use common string properties and methods
  • Turn strings into numbers and numbers into strings

1. String Literals

A literal is a value written directly in the code. A string literal is text inside quotes, and single and double quotes mean exactly the same thing:

dart
var a = 'Hello';
var b = "Hello";
print(a == b);   // true

Pick one style and stick to it. Most Dart code uses single quotes. Double quotes are handy when the text itself has an apostrophe:

dart
var mixed = "It's sunny";     // no problem inside double quotes
var escaped = 'It\'s sunny';  // or escape it with a backslash

2. Escape Characters and Raw Strings

A backslash \ gives the next character a special meaning:

EscapeMeans
\nnew line
\ttab
\'a single quote
\"a double quote
\\a real backslash
\$a real dollar sign
dart
print('Line 1\nLine 2');
print('Name:\tAli');
print('Path: C:\\Users');

Output

code
Line 1
Line 2
Name:	Ali
Path: C:\Users

Put an r in front of the quotes for a raw string: backslashes are kept exactly as typed.

dart
print(r'Path: C:\Users\new');   // Path: C:\Users\new

3. Multi-Line Strings

Three quotes (''' or """) let a string span several lines:

dart
var poem = '''
Roses are red,
Dart is fun.''';
print(poem);

Output

code
Roses are red,
Dart is fun.

4. String Interpolation

Interpolation puts a value inside a string. Write $ followed by a variable name:

dart
var name = 'Ayesha';
var age = 19;
print('My name is $name and I am $age years old.');

For anything more than a plain variable name (a calculation, a property, a method call), wrap it in ${ }:

dart
print('Next year I will be ${age + 1}.');
print('Name has ${name.length} letters.');
print('Price: \$50');   // \$ prints a real dollar sign

Output

code
My name is Ayesha and I am 19 years old.
Next year I will be 20.
Name has 6 letters.
Price: $50

5. Joining Strings

The + operator joins two strings. Two literals written side by side are joined automatically.

dart
var first = 'Coding';
var last = 'Mentor';
print(first + ' ' + last);   // Coding Mentor
print('Coding ' 'Mentor');   // Coding Mentor

When a variable is involved, interpolation ('$first $last') is shorter and easier to read than +, and it is what most Dart code uses.

6. Useful Properties and Methods

dart
var word = '  Dart Programming  ';

print(word.length);                                     // 20 (the spaces count)
print(word.trim());                                     // Dart Programming
print(word.trim().toUpperCase());                       // DART PROGRAMMING
print(word.trim().toLowerCase());                       // dart programming
print(word.contains('Dart'));                           // true
print(word.trim().startsWith('Dart'));                  // true
print(word.trim().replaceAll('Programming', 'Basics')); // Dart Basics
print(word.trim().split(' '));                          // [Dart, Programming]
print('Dart'[0]);                                       // D (positions start at 0)
print('Dart'.substring(1, 3));                          // ar (from 1, up to but not including 3)
print(''.isEmpty);                                      // true
ToolWhat it does
lengthnumber of characters
trim()removes spaces from both ends
toUpperCase() / toLowerCase()changes the case
contains(x)is x somewhere inside?
startsWith(x) / endsWith(x)does it begin or end with x?
replaceAll(a, b)swaps every a for b
split(x)cuts the string into a list at each x
[i]the character at position i
substring(start, end)a piece of the string
isEmpty / isNotEmptyis it ''?

7. Strings Never Change

A string can't be changed in place. Methods like toUpperCase() give you a new string and leave the original alone:

dart
var greeting = 'hello';
greeting.toUpperCase();          // makes 'HELLO', then throws it away
print(greeting);                 // hello

greeting = greeting.toUpperCase();  // keep the new string
print(greeting);                 // HELLO

8. Strings and Numbers

Text from a user or a file always arrives as a String, even when it looks like a number. Convert it before doing maths:

dart
print(int.parse('42') + 8);          // 50
print(double.parse('3.5') * 2);      // 7.0
print(42.toString() + '!');          // 42!
print(3.14159.toStringAsFixed(2));   // 3.14

int.parse crashes if the text isn't a whole number. Lecture 010 shows a safer way, int.tryParse.


Code Examples

Example 1: A Shop Receipt

dart
void main() {
  const shop = 'Corner Store';
  final customer = '  sara khan  ';
  final items = 3;
  final price = 249.5;

  final cleanName = customer.trim();
  final total = items * price;

  print('=' * 24);
  print(shop.toUpperCase());
  print('=' * 24);
  print('Customer: $cleanName');
  print('Initials: ${cleanName[0].toUpperCase()}${cleanName.split(' ')[1][0].toUpperCase()}');
  print('Items:\t$items');
  print('Total:\tRs ${total.toStringAsFixed(2)}');
  print('Thank you, ${cleanName.split(' ')[0]}!');
}

Output

code
========================
CORNER STORE
========================
Customer: sara khan
Initials: SK
Items:	3
Total:	Rs 748.50
Thank you, sara!

'=' * 24 repeats a string 24 times, which is a quick way to draw a line.


Common Beginner Mistakes

1. Adding a number to a string with +

dart
var age = 19;
print('Age: ' + age);
code
Error: A value of type 'int' can't be assigned to a variable of type 'String'.
  print('Age: ' + age);
                  ^

Use interpolation instead: print('Age: $age');

2. An apostrophe inside single quotes

dart
var text = 'It's sunny';
code
Error: String starting with ' must end with '.
  var text = 'It's sunny';
                        ^^

Dart thinks the string ends at It. Write "It's sunny" or 'It\'s sunny'.

3. Forgetting the braces

dart
var name = 'Ali';
print('Hello, $name.length');   // Hello, Ali.length

No error, but the wrong output: $name stops at the dot. Write ${name.length}.

4. Expecting a method to change the string: name.toUpperCase(); on its own does nothing you can see. Save the result: name = name.toUpperCase();

5. Parsing text that isn't a number: int.parse('12a') crashes the program:

code
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
12a
^

6. Naming a variable after a type: var double = "Hello"; hides Dart's double type, so a later double.parse(...) in the same function stops working. Use names that describe the value, like price or greeting.


Practice Questions

  1. What does print('Total: ${2 * 5}'); print?
  2. Write a string that prints exactly: She said "hi"
  3. What is ' Lahore '.trim().length?
  4. What does print(r'\n'); print?
  5. After var city = 'multan'; city.toUpperCase();, what is city?
  6. Turn the string '25' into a number and add 5 to it.
  7. What does 'Flutter'.substring(0, 4) give?

Practice Answers

  1. Total: 10
  2. print('She said "hi"');, or print("She said \"hi\"");
  3. 6, because trim() removes the spaces, leaving Lahore.
  4. \n (two characters): a raw string keeps the backslash.
  5. Still multan. The uppercase copy was never saved.
  6. int.parse('25') + 5, which is 30.
  7. Flut

Key Takeaways

  • Strings are text in 'single' or "double" quotes; '''triple''' quotes span lines.
  • \n, \t, \', \\ and \$ are escapes; r'...' turns escapes off.
  • $name puts a variable in a string; ${...} puts any expression in.
  • Prefer interpolation over + when mixing text and values.
  • String methods return a new string; the original never changes.
  • Use int.parse / double.parse to read numbers and toString() to write them.