On this page15 sections
- Prerequisites
- Learning Objectives
- 1. String Literals
- 2. Escape Characters and Raw Strings
- 3. Multi-Line Strings
- 4. String Interpolation
- 5. Joining Strings
- 6. Useful Properties and Methods
- 7. Strings Never Change
- 8. Strings and Numbers
- Code Examples
- Common Beginner Mistakes
- Practice Questions
- Practice Answers
- Key Takeaways
Lecture 009: Strings, Literals & Interpolation
| Day | 4: Strings & Null Safety |
| Lecture | 009 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
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 (
$nameand${...}) - 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:
var a = 'Hello';
var b = "Hello";
print(a == b); // truePick one style and stick to it. Most Dart code uses single quotes. Double quotes are handy when the text itself has an apostrophe:
var mixed = "It's sunny"; // no problem inside double quotes
var escaped = 'It\'s sunny'; // or escape it with a backslash2. Escape Characters and Raw Strings
A backslash \ gives the next character a special meaning:
| Escape | Means |
|---|---|
\n | new line |
\t | tab |
\' | a single quote |
\" | a double quote |
\\ | a real backslash |
\$ | a real dollar sign |
print('Line 1\nLine 2');
print('Name:\tAli');
print('Path: C:\\Users');Output
Line 1
Line 2
Name: Ali
Path: C:\UsersPut an r in front of the quotes for a raw string: backslashes are kept exactly as typed.
print(r'Path: C:\Users\new'); // Path: C:\Users\new3. Multi-Line Strings
Three quotes (''' or """) let a string span several lines:
var poem = '''
Roses are red,
Dart is fun.''';
print(poem);Output
Roses are red,
Dart is fun.4. String Interpolation
Interpolation puts a value inside a string. Write $ followed by a variable name:
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 ${ }:
print('Next year I will be ${age + 1}.');
print('Name has ${name.length} letters.');
print('Price: \$50'); // \$ prints a real dollar signOutput
My name is Ayesha and I am 19 years old.
Next year I will be 20.
Name has 6 letters.
Price: $505. Joining Strings
The + operator joins two strings. Two literals written side by side are joined automatically.
var first = 'Coding';
var last = 'Mentor';
print(first + ' ' + last); // Coding Mentor
print('Coding ' 'Mentor'); // Coding MentorWhen 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
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| Tool | What it does |
|---|---|
length | number 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 / isNotEmpty | is 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:
var greeting = 'hello';
greeting.toUpperCase(); // makes 'HELLO', then throws it away
print(greeting); // hello
greeting = greeting.toUpperCase(); // keep the new string
print(greeting); // HELLO8. 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:
print(int.parse('42') + 8); // 50
print(double.parse('3.5') * 2); // 7.0
print(42.toString() + '!'); // 42!
print(3.14159.toStringAsFixed(2)); // 3.14int.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
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
========================
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 +
var age = 19;
print('Age: ' + age);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
var text = 'It's sunny';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
var name = 'Ali';
print('Hello, $name.length'); // Hello, Ali.lengthNo 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:
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
- What does
print('Total: ${2 * 5}');print? - Write a string that prints exactly:
She said "hi" - What is
' Lahore '.trim().length? - What does
print(r'\n');print? - After
var city = 'multan'; city.toUpperCase();, what iscity? - Turn the string
'25'into a number and add5to it. - What does
'Flutter'.substring(0, 4)give?
Practice Answers
Total: 10print('She said "hi"');, orprint("She said \"hi\"");6, becausetrim()removes the spaces, leavingLahore.\n(two characters): a raw string keeps the backslash.- Still
multan. The uppercase copy was never saved. int.parse('25') + 5, which is30.Flut
Key Takeaways
- Strings are text in
'single'or"double"quotes;'''triple'''quotes span lines. \n,\t,\',\\and\$are escapes;r'...'turns escapes off.$nameputs 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.parseto read numbers andtoString()to write them.