String Interpolation
String interpolation is a powerful feature in Dart that allows you to embed expressions and variables directly inside strings. Think of it as a way to "inject" values into your strings without having to concatenate them manually!
Basic String Interpolation
In Dart, you use the $ symbol followed by a variable name to interpolate simple variables:
void main() {
String name = 'Alice';
int age = 25;
print('Hello, my name is $name and I am $age years old.');
// Output: Hello, my name is Alice and I am 25 years old.
}
Expression Interpolation
For more complex expressions, you wrap them in curly braces ${}:
void main() {
int length = 10;
int width = 5;
print('The area of the rectangle is ${length * width} square units.');
// Output: The area of the rectangle is 50 square units.
String firstName = 'John';
String lastName = 'Doe';
print('Full name: ${firstName.toUpperCase()} ${lastName.toUpperCase()}');
// Output: Full name: JOHN DOE
}
When to Use Curly Braces
Use $variable | Use ${expression} |
|---|---|
| Simple variable names | Complex expressions |
$name, $age | ${name.length}, ${x + y} |
| No method calls | Method calls like ${text.toUpperCase()} |
| No operators | Mathematical operations like ${a * b} |
Practical Examples
Here are some common use cases for string interpolation:
void main() {
// Working with numbers
double price = 29.99;
int quantity = 3;
print('Total cost: \$${(price * quantity).toStringAsFixed(2)}');
// Output: Total cost: $89.97
// Working with lists
List<String> fruits = ['apple', 'banana', 'orange'];
print('I have ${fruits.length} fruits: ${fruits.join(', ')}');
// Output: I have 3 fruits: apple, banana, orange
// Conditional expressions
int score = 85;
print('Result: ${score >= 60 ? 'Pass' : 'Fail'}');
// Output: Result: Pass
}
Why Use String Interpolation?
String interpolation makes your code:
- More readable: Compare
'Hello $name'vs'Hello ' + name - More efficient: Dart optimizes interpolated strings
- Less error-prone: No need to worry about missing spaces or plus signs
It's like having a template where you can fill in the blanks with actual values - much cleaner than gluing strings together piece by piece!