Trusted answers to developer questions

How to create a raw string in Dart

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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
}

RELATED TAGS

escape
backslash
string
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?