How to create a raw string in Dart

Raw strings treat backslashes (\) as a literal character. In a normal string, a backslash acts as an escape character that can be used for various purposes.

The escape character

Here is an example of \n starting a new line and \t adding a tab in between the string:

void main(){
String str1 = "First line \nSecond line";
print(str1);
String str2 = "First line \tSecond line";
print(str2);
}

If str1 and str2 were raw strings, \n and \t would be treated as literal characters.

The literal character

In Dart, a raw string can be created by prepending an r to a string:

void main(){
String str1 = r'First line \nSecond line';
print(str1);
String str2 = r'First line \tSecond line';
print(str2);
print(r'\'); // Single backslash
}

The single backslash in line 8 cannot be printed without r. If it is, the backslash will be treated as an escape character.

In conclusion, the raw string type can be used whenever an actual backslash is required within a string.

svg viewer

An alternative way to obtain a backslash within a string is to write two backslashes​ instead of one. The first backslash will act as an escape character for the second one:

void main(){
String str = 'First line \\nSecond line';
print(str);
print('\\'); // Single backslash
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved