How to print the dollar sign in Dart

Published by admin on

Introduction :

You can’t directly print the dollar($) symbol in dart. It is used only with an identifier or an expression in curly braces. For example :

main() {
  var s = "Hello $ World";
  print(s);
}

It will throw one error :

Error: A '$' has special meaning inside a string, and must be followed by an identifier or an expression in curly braces ({}).
Try adding a backslash (\) to escape the '$'.
  var s = "Hello $ World";

We can either add one backslash or use one raw string to print it.

 

Example 1 : Using backslash :

main() {
  var s = "Hello \$ World";
  print(s);
}

Output :

Hello $ World

Dart print dollar backslash

 

Example 2: Using raw string :

Raw string can be created by prepending an ‘r’ to a string. It treats $ as a literal character.

main() {
  var s = r'Hello $ World';
  print(s);
}

Output :

Hello $ World

Dart print dollar raw string

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *