How to print dollar symbol in string dart?| Flutter By Example
You can concatenate strings using the plus operator or interpolation syntax.
Similarly, you can include a dollar symbol in a string in multiple ways.
How to Print the Dollar Symbol in Dart and Flutter?
There are several methods:
When the string contains regular text or raw text interpreted with interpolation syntax. Interpolation syntax uses the $
symbol to represent the variable’s value. For instance, by using $price
, you can insert the variable value. However, appending $
to an interpolated variable triggers an error. The error message states:
A ’$’ has a special meaning inside a string, and must be followed by an identifier or an expression in curly braces ().
The following code demonstrates this error:
void main() {
int price = 95;
print("Current price is $$price");
}
To resolve this, one approach is to escape the $
symbol as \$
.
void main() {
int price = 95;
print("Current price is \$$price");
}
Another method involves using a raw string, indicated by the prefix r
.
void main() {
int price = 95;
print(r"Current price is $price");
}
Conclusion
It’s important to note that raw strings treat the $
symbol differently. To print a dollar symbol, it needs to be escaped.