Mastering String Quotes in Dart: Single, Double, and Triple Quotes Explained
In Dart, single quotes ('
) and double quotes ("
) are used interchangeably to create strings. Dart does not distinguish between the two, so you can use either one according to your preference or needs to avoid conflicts with characters within the string.
Here are some examples of their usage:
Using Single Quotes ('
)
void main() {
String singleQuoteString = 'Hello, World!';
print(singleQuoteString); // Output: Hello, World!
}
Using Double Quotes ("
)
void main() {
String doubleQuoteString = "Hello, World!";
print(doubleQuoteString); // Output: Hello, World!
}
Avoiding Conflicts with Characters within the String
If your string contains a single quote, use double quotes to define the string, and vice versa:
Using Double Quotes within a String Defined with Single Quotes
void main() {
String message = 'She said, "Hello, World!"';
print(message); // Output: She said, "Hello, World!"
}
Using Single Quotes within a String Defined with Double Quotes
void main() {
String message = "It's a beautiful day!";
print(message); // Output: It's a beautiful day!
}
Using Triple Quotes for Multi-Line Strings
Dart also supports the use of triple quotes (both single and double) to define multi-line strings:
Triple Single Quotes ('''
)
void main() {
String multiLineString = '''
This is a string
that spans multiple
lines.
''';
print(multiLineString);
}
Triple Double Quotes ("""
)
void main() {
String multiLineString = """
This is a string
that spans multiple
lines.
""";
print(multiLineString);
}
Example of Triple Quotes ("""
)
Escaping Characters within the String
You can also use the escape character (\
) to include quotes within a string defined with the same type of quote:
void main() {
String singleQuoteString = 'It\'s a beautiful day!';
String doubleQuoteString = "She said, \"Hello, World!\"";
print(singleQuoteString); // Output: It's a beautiful day!
print(doubleQuoteString); // Output: She said, "Hello, World!"
}
Overall, Dart provides flexibility in using quotes to define strings, allowing you to choose the style that best suits your coding needs.