Strings & String Interpolation
Creating Strings in Dart
Strings are one of the most commonly used data types in any programming language. In Dart, a String is a sequence of UTF-16 code units, meaning it supports international characters, emojis, and special symbols out of the box. You can create strings using single quotes, double quotes, or triple quotes.
String Literals
void main() {
// Single quotes (preferred in Dart)
String greeting = 'Hello, World!';
// Double quotes (also valid)
String message = "Welcome to Dart";
// Both are identical -- choose one style and be consistent
print(greeting); // Hello, World!
print(message); // Welcome to Dart
}
Escape Characters
Sometimes you need to include special characters inside a string. Use the backslash (\) as an escape character:
Common Escape Sequences
void main() {
// Newline
print('First line\nSecond line');
// Tab
print('Name:\tEdrees');
// Single quote inside single-quoted string
print('It\'s a great day!');
// Double quote inside double-quoted string
print("She said \"Hello\"");
// Backslash itself
print('Path: C:\Users\Dart');
// Dollar sign (without interpolation)
print('Price: \$99.99');
}
Raw Strings
If you want to disable all escape sequences, prefix the string with r. This is useful for file paths and regular expressions.
Raw Strings with r Prefix
void main() {
// Normal string -- \n is a newline
print('Hello\nWorld');
// Output:
// Hello
// World
// Raw string -- \n is treated as literal text
print(r'Hello\nWorld');
// Output: Hello\nWorld
// Useful for regex patterns
String pattern = r'\d{3}-\d{4}';
print(pattern); // \d{3}-\d{4}
// Useful for Windows file paths
String path = r'C:\Users\Documents\file.txt';
print(path); // C:\Users\Documents\file.txt
}
Multi-Line Strings
Use triple quotes (''' or """) to create strings that span multiple lines without needing \n:
Multi-Line Strings
void main() {
String poem = '''
Roses are red,
Violets are blue,
Dart is awesome,
And so are you!
''';
print(poem);
// Also works with double quotes
String json = """
{
"name": "Edrees",
"language": "Dart"
}
""";
print(json);
}
String Interpolation
String interpolation is one of Dart’s most powerful features. Instead of concatenating strings with the + operator, you embed variables and expressions directly inside the string using the $ symbol.
Simple Variable Interpolation
Use $variableName to insert a variable’s value:
Basic Interpolation
void main() {
String name = 'Edrees';
int age = 28;
String language = 'Dart';
// With interpolation (recommended)
print('My name is $name and I am $age years old.');
print('I am learning $language!');
// Without interpolation (not recommended)
print('My name is ' + name + ' and I am ' + age.toString() + ' years old.');
}
+. It is cleaner, more readable, and avoids the need to manually call .toString() on non-string values.Expression Interpolation
Use ${expression} for anything more complex than a simple variable name -- calculations, method calls, or property access:
Expression Interpolation with ${}
void main() {
int a = 10;
int b = 20;
// Arithmetic expression
print('The sum of $a and $b is ${a + b}');
// Output: The sum of 10 and 20 is 30
// Method calls
String name = 'edrees salih';
print('Uppercase: ${name.toUpperCase()}');
// Output: Uppercase: EDREES SALIH
// Property access
List<int> numbers = [1, 2, 3, 4, 5];
print('The list has ${numbers.length} items');
// Output: The list has 5 items
// Conditional expression
int score = 85;
print('Result: ${score >= 60 ? "Pass" : "Fail"}');
// Output: Result: Pass
}
String Concatenation
While interpolation is preferred, Dart supports several ways to combine strings:
Ways to Combine Strings
void main() {
// 1. Using + operator
String first = 'Hello';
String second = 'World';
String combined = first + ' ' + second;
print(combined); // Hello World
// 2. Adjacent string literals (automatically joined)
String auto = 'Hello '
'World '
'from Dart';
print(auto); // Hello World from Dart
// 3. StringBuffer for many concatenations (efficient)
var buffer = StringBuffer();
buffer.write('Hello');
buffer.write(' ');
buffer.write('World');
print(buffer.toString()); // Hello World
}
StringBuffer instead of +. The + operator creates a new String object each time, while StringBuffer modifies the same buffer, making it much more memory-efficient.Useful String Properties
Every String in Dart comes with helpful properties:
String Properties
void main() {
String text = 'Hello, Dart!';
print(text.length); // 12 (number of characters)
print(text.isEmpty); // false
print(text.isNotEmpty); // true
String empty = '';
print(empty.isEmpty); // true
print(empty.length); // 0
}
Common String Methods
Dart provides many built-in methods for working with strings. Here are the most important ones:
Case Conversion
void main() {
String name = 'Edrees Salih';
print(name.toUpperCase()); // EDREES SALIH
print(name.toLowerCase()); // edrees salih
}
Trimming Whitespace
void main() {
String padded = ' Hello, World! ';
print(padded.trim()); // 'Hello, World!'
print(padded.trimLeft()); // 'Hello, World! '
print(padded.trimRight()); // ' Hello, World!'
}
Searching in Strings
void main() {
String sentence = 'Dart is fun and Dart is powerful';
print(sentence.contains('fun')); // true
print(sentence.startsWith('Dart')); // true
print(sentence.endsWith('powerful')); // true
print(sentence.indexOf('Dart')); // 0 (first occurrence)
print(sentence.lastIndexOf('Dart')); // 16 (last occurrence)
}
Replacing and Splitting
void main() {
String text = 'Hello World';
// Replace
print(text.replaceAll('World', 'Dart')); // Hello Dart
// Split into a list
String csv = 'apple,banana,orange';
List<String> fruits = csv.split(',');
print(fruits); // [apple, banana, orange]
// Substring
print(text.substring(0, 5)); // Hello
print(text.substring(6)); // World
}
Padding and Repeating
void main() {
String id = '42';
// Pad to a minimum length
print(id.padLeft(5, '0')); // 00042
print(id.padRight(5, '-')); // 42---
// Repeat a string
String line = '=-' * 10;
print(line); // =-=-=-=-=-=-=-=-=-=-
}
String Comparison
Strings in Dart are compared by their content, not by reference:
Comparing Strings
void main() {
String a = 'Dart';
String b = 'Dart';
String c = 'dart';
print(a == b); // true (same content)
print(a == c); // false (case-sensitive)
// Case-insensitive comparison
print(a.toLowerCase() == c.toLowerCase()); // true
// compareTo returns 0 if equal, negative or positive otherwise
print(a.compareTo(b)); // 0
}
Type Conversion with Strings
Converting between strings and other types is a common task:
Converting To and From Strings
void main() {
// Number to String
int age = 28;
String ageStr = age.toString();
print(ageStr); // '28'
double price = 9.99;
String priceStr = price.toString();
print(priceStr); // '9.99'
// String to Number
String numStr = '42';
int number = int.parse(numStr);
print(number); // 42
String decStr = '3.14';
double decimal = double.parse(decStr);
print(decimal); // 3.14
// Safe parsing (returns null instead of throwing)
int? safe = int.tryParse('abc');
print(safe); // null (no error thrown)
int? valid = int.tryParse('100');
print(valid); // 100
}
int.parse() or double.parse() with invalid input will throw a FormatException. Always use tryParse() when dealing with user input or data from external sources, as it returns null instead of crashing.Strings Are Immutable
An important concept: strings in Dart are immutable. Every operation that seems to modify a string actually creates a new string. The original remains unchanged.
Immutability Demonstrated
void main() {
String original = 'Hello';
String upper = original.toUpperCase();
print(original); // Hello (unchanged!)
print(upper); // HELLO (new string)
}
Practice Exercise
Open DartPad and build a program that: (1) Creates variables for a person’s first name, last name, age, and city. (2) Uses string interpolation to print a formatted introduction like “Hi, I am [name], [age] years old from [city].” (3) Converts the full name to uppercase and counts its length. (4) Splits a comma-separated string of hobbies into a list and prints each hobby. (5) Uses tryParse to safely convert a user-entered string to an integer.