In Dart, the dollar sign ($) has a special meaning when used within string literals. It is used for string interpolation, which allows you to embed expressions within a string. Here's how it works:
Basic String Interpolation: You can use the dollar sign followed by curly braces (${expression}) to insert the value of an expression into a string. The expression will be evaluated and its result will be converted to a string and inserted into the string literal.
var name = 'John';
var age = 30;
var message = 'My name is $name and I am $age years old.';
print(message); // Output: My name is John and I am 30 years old.
Expression Evaluation: The expression within the curly braces can be any valid Dart expression, including method calls, arithmetic operations, or even nested expressions.
var x = 5;
var y = 10;
var result = 'The sum of $x and $y is ${x + y}.';
print(result); // Output: The sum of 5 and 10 is 15.
Object Properties and Methods: You can also access properties and call methods on objects using string interpolation.
var person = Person('Alice', 25);
var greeting = 'Hello, my name is ${
person.name
} and I am ${person.age} years old.';
print(greeting); // Output: Hello, my name is Alice and I am 25 years old.
Escaping the Dollar Sign: If you want to include a literal dollar sign within a string, you can escape it by using two consecutive dollar signs ($$).
var price = 10;
var message = 'The cost is $$price.'; // Use \ to escape the dollar sign
print(message); // Output: The cost is $10.
String interpolation with the dollar sign ($) provides a convenient way to build dynamic strings by including values from variables or expressions.